home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python-1.4 / Docs / Python_FAQ.txt < prev    next >
Text File  |  1998-06-24  |  100KB  |  2,258 lines

  1. Subject: FAQ: Python -- an object-oriented language
  2. Newsgroups: comp.lang.python,comp.answers,news.answers
  3. Followup-to: comp.lang.python
  4. From: guido@cnri.reston.va.us (Guido van Rossum)
  5. Reply-to: guido@cnri.reston.va.us (Guido van Rossum)
  6. Expires: Sun, 1 Dec 1996 00:00:00 GMT
  7. Supersedes: <DxJ3t1.CJv@cwi.nl>
  8. Approved: news-answers-request@MIT.Edu
  9.  
  10. Archive-name: python-faq/part1
  11. Submitted-by: Guido van Rossum <guido@cnri.reston.va.us>
  12. Version: $Revision: 1.39 $
  13. Last-modified: $Date: 1996/10/23 20:52:55 $
  14.  
  15. This article contains answers to Frequently Asked Questions about
  16. Python (an object-oriented interpreted programming language -- see
  17. the answer to question 1.1 for a short overview).
  18.  
  19. Copyright 1993-1996 Guido van Rossum.  Unchanged electronic
  20. redistribution of this FAQ is allowed.  Printed redistribution only
  21. with permission of the author.  No warranties.
  22.  
  23. Author's address:
  24.         Guido van Rossum
  25.         C.N.R.I.
  26.         1895 Preston White Drive
  27.         Reston, VA 20191
  28.         U.S.A.
  29. Email:  <guido@python.org>, <guido@cnri.reston.va.us>
  30.  
  31. The latest version of this FAQ is available by anonymous ftp from
  32. <URL:ftp://ftp.python.org/pub/python/doc/FAQ>.  It will also be posted
  33. regularly to the newsgroups comp.answers <URL:news:comp.answers> and
  34. comp.lang.python <URL:news:comp.lang.python>.
  35.  
  36. Many FAQs, including this one, are available by anonymous ftp
  37. <URL:ftp://rtfm.mit.edu/pub/usenet/news.answers/>.  The name under
  38. which a FAQ is archived appears in the Archive-name line at the top of
  39. the article.  This FAQ is archived as python-faq/part1
  40. <URL:ftp://rtfm.mit.edu/pub/usenet/news.answers/python-faq/part1>.
  41.  
  42. There's a mail server on that machine which will send you files from
  43. the archive by e-mail if you have no ftp access.  You send a e-mail
  44. message to <mail-server@rtfm.mit.edu> containing the single word help
  45. in the message body to receive instructions.
  46.  
  47. This FAQ is divided in the following chapters:
  48.  
  49.  1. General information and availability
  50.  2. Python in the real world
  51.  3. Building Python and Other Known Bugs
  52.  4. Programming in Python
  53.  5. Extending Python
  54.  6. Python's design
  55.  7. Using Python on non-UNIX platforms
  56.  
  57. To find the start of a particular chapter, search for the chapter number
  58. followed by a dot and a space at the beginning of a line (e.g. to
  59. find chapter 4 in vi, type /^4\. /).
  60.  
  61. Here's an overview of the questions per chapter:
  62.  
  63.  1. General information and availability
  64.   1.1. Q. What is Python?
  65.   1.2. Q. Why is it called Python?
  66.   1.3. Q. How do I obtain a copy of the Python source?
  67.   1.4. Q. How do I get documentation on Python?
  68.   1.5. Q. Are there other ftp sites that mirror the Python distribution?
  69.   1.6. Q. Is there a newsgroup or mailing list devoted to Python?
  70.   1.7. Q. Is there a WWW page devoted to Python?
  71.   1.8. Q. Is the Python documentation available on the WWW?
  72.   1.9. Q. Is there a book on Python, or will there be one out soon?
  73.   1.10. Q. Are there any published articles about Python that I can quote?
  74.   1.11. Q. Are there short introductory papers or talks on Python?
  75.   1.12. Q. How does the Python version numbering scheme work?
  76.   1.13. Q. How do I get a beta test version of Python?
  77.   1.14. Q. Are there copyright restrictions on the use of Python?
  78.   1.15. Q. Why was Python created in the first place?
  79.  
  80.  2. Python in the real world
  81.   2.1. Q. How many people are using Python?
  82.   2.2. Q. Have any significant projects been done in Python?
  83.   2.3. Q. Are there any commercial projects going on using Python?
  84.   2.4. Q. How stable is Python?
  85.   2.5. Q. What new developments are expected for Python in the future?
  86.   2.6. Q. Is it reasonable to propose incompatible changes to Python?
  87.   2.7. Q. What is the future of Python?
  88.   2.8. Q. What is the PSA, anyway?
  89.   2.9. Q. How do I join the PSA?
  90.   2.10. Q. What are the benefits of joining the PSA?
  91.  
  92.  3. Building Python and Other Known Bugs
  93.   3.1. Q. Is there a test set?
  94.   3.2. Q. When running the test set, I get complaints about floating point
  95.        operations, but when playing with floating point operations I cannot
  96.        find anything wrong with them.
  97.   3.3. Q. Link errors after rerunning the configure script.
  98.   3.4. Q. The python interpreter complains about options passed to a
  99.        script (after the script name).
  100.   3.5. Q. When building on the SGI, make tries to run python to create
  101.        glmodule.c, but python hasn't been built or installed yet.
  102.   3.6. Q. I use VPATH but some targets are built in the source directory.
  103.   3.7. Q. Trouble building or linking with the GNU readline library.
  104.   3.8. Q. Trouble with socket I/O on older Linux 1.x versions.
  105.   3.9. Q. Trouble with prototypes on Ultrix.
  106.   3.10. Q. Other trouble building Python on platform X.
  107.   3.11. Q. How to configure dynamic loading on Linux.
  108.   3.12. Q: I can't get shared modules to work on Linux 2.0 (Slackware96)?
  109.   3.13. Q. How to use threads on Linux.
  110.   3.14. Q. Errors when linking with a shared library containing C++ code.
  111.   3.15. Q. I built with tkintermodule.c enabled but get "Tkinter not found".
  112.   3.16. Q. I built with Tk 4.0 but Tkinter complains about the Tk version.
  113.   3.17. Q. Link errors for Tcl/Tk symbols when linking with Tcl/Tk.
  114.   3.18. Q. I configured and built Python for Tcl/Tk but "import Tkinter"
  115.         fails.
  116.   3.19. Q. Tk doesn't work right on DEC Alpha.
  117.   3.20. Q. Several common system calls are missing from the posix module.
  118.   3.21. Q. ImportError: No module named string, on MS Windows.
  119.   3.22. Q. Core dump on SGI when using the gl module.
  120.  
  121.  4. Programming in Python
  122.   4.1. Q. Is there a source code level debugger with breakpoints, step,
  123.        etc.?
  124.   4.2. Q. Can I create an object class with some methods implemented in
  125.        C and others in Python (e.g. through inheritance)?  (Also phrased as:
  126.        Can I use a built-in type as base class?)
  127.   4.3. Q. Is there a curses/termcap package for Python?
  128.   4.4. Q. Is there an equivalent to C's onexit() in Python?
  129.   4.5. Q. When I define a function nested inside another function, the
  130.        nested function seemingly can't access the local variables of the
  131.        outer function.  What is going on?  How do I pass local data to a
  132.        nested function?
  133.   4.6. Q. How do I iterate over a sequence in reverse order?
  134.   4.7. Q. My program is too slow.  How do I speed it up?
  135.   4.8. Q. When I have imported a module, then edit it, and import it
  136.        again (into the same Python process), the changes don't seem to take
  137.        place.  What is going on?
  138.   4.9. Q. How do I find the current module name?
  139.   4.10. Q. I have a module in which I want to execute some extra code
  140.         when it is run as a script.  How do I find out whether I am running as
  141.         a script?
  142.   4.11. Q. I try to run a program from the Demo directory but it fails
  143.         with ImportError: No module named ...; what gives?
  144.   4.12. Q. I have successfully built Python with STDWIN but it can't
  145.         find some modules (e.g. stdwinevents).
  146.   4.13. Q. What GUI toolkits exist for Python?
  147.   4.14. Q. Are there any interfaces to database packages in Python?
  148.   4.15. Q. Is it possible to write obfuscated one-liners in Python?
  149.   4.16. Q. Is there an equivalent of C's "?:" ternary operator?
  150.   4.17. Q. My class defines __del__ but it is not called when I delete the
  151.         object.
  152.   4.18. Q. How do I change the shell environment for programs called
  153.         using os.popen() or os.system()?  Changing os.environ doesn't work.
  154.   4.19. Q. What is a class?
  155.   4.20. Q. What is a method?
  156.   4.21. Q. What is self?
  157.   4.22. Q. What is a unbound method?
  158.   4.23. Q. How do I call a method defined in a base class from a derived
  159.         class that overrides it?
  160.   4.24. Q. How do I call a method from a base class without using the
  161.         name of the base class?
  162.   4.25. Q. How can I organize my code to make it easier to change the base
  163.         class?
  164.   4.26. Q. How can I find the methods or attributes of an object?
  165.   4.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
  166.   4.28. Q. How can I create a stand-alone binary from a Python script?
  167.   4.29. Q. What WWW tools are there for Python?
  168.   4.30. Q. How do I run a subprocess with pipes connected to both input
  169.         and output?
  170.   4.31. Q. How do I call a function if I have the arguments in a tuple?
  171.   4.32. Q. How do I enable font-lock-mode for Python in Emacs?
  172.   4.33. Q. Is there an inverse to the format operator (a la C's scanf())?
  173.   4.34. Q. Can I have Tk events handled while waiting for I/O?
  174.   4.35. Q. How do I write a function with output parameters (call by reference)?
  175.   4.36. Q. Please explain the rules for local and global variables in Python.
  176.   4.37. Q. How can I have modules that mutually import each other?
  177.   4.38. Q. How do I copy an object in Python?
  178.   4.39. Q. How to implement persistent objects in Python?  (Persistent ==
  179.         automatically saved to and restored from disk.)
  180.   4.40. Q. I try to use __spam and I get an error about _SomeClassName__spam.
  181.  
  182.  5. Extending Python
  183.   5.1. Q. Can I create my own functions in C?
  184.   5.2. Q. Can I create my own functions in C++?
  185.   5.3. Q. How can I execute arbitrary Python statements from C?
  186.   5.4. Q. How can I evaluate an arbitrary Python expression from C?
  187.   5.5. Q. How do I extract C values from a Python object?
  188.   5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
  189.   5.7. Q. How do I call an object's method from C?
  190.   5.8. Q. How do I catch the output from print_error()?
  191.   5.9. Q. How do I access a module written in Python from C?
  192.   5.10. Q. How do I interface to C++ objects from Python?
  193.  
  194.  6. Python's design
  195.   6.1. Q. Why isn't there a switch or case statement in Python?
  196.   6.2. Q. Why does Python use indentation for grouping of statements?
  197.   6.3. Q. Why are Python strings immutable?
  198.   6.4. Q. Why don't strings have methods like index() or sort(), like
  199.        lists?
  200.   6.5. Q. Why does Python use methods for some functionality
  201.        (e.g. list.index()) but functions for other (e.g. len(list))?
  202.   6.6. Q. Why can't I derive a class from built-in types (e.g. lists or
  203.        files)?
  204.   6.7. Q. Why must 'self' be declared and used explicitly in method
  205.        definitions and calls?
  206.   6.8. Q. Can't you emulate threads in the interpreter instead of
  207.        relying on an OS-specific thread implementation?
  208.   6.9. Q. Why can't lambda forms contain statements?
  209.   6.10. Q. Why don't lambdas have access to variables defined in the
  210.         containing scope?
  211.   6.11. Q. Why can't recursive functions be defined inside other functions?
  212.   6.12. Q. Why is there no more efficient way of iterating over a dictionary
  213.         than first constructing the list of keys()?
  214.   6.13. Q. Can Python be compiled to machine code, C or some other language?
  215.   6.14. Q. Why doesn't Python use proper garbage collection?
  216.  
  217.  7. Using Python on non-UNIX platforms
  218.   7.1. Q. Is there a Mac version of Python?
  219.   7.2. Q. Are there DOS and Windows versions of Python?
  220.   7.3. Q. Is there an OS/2 version of Python?
  221.   7.4. Q. Is there a VMS version of Python?
  222.   7.5. Q. What about IBM mainframes, or other non-UNIX platforms?
  223.   7.6. Q. Where are the source or Makefiles for the non-UNIX versions?
  224.   7.7. Q. What is the status and support for the non-UNIX versions?
  225.   7.8. Q. I have a PC version but it appears to be only a binary.
  226.        Where's the library?
  227.   7.9. Q. Where's the documentation for the Mac or PC version?
  228.   7.10. Q. The Mac (PC) version doesn't seem to have any facilities for
  229.         creating or editing programs apart from entering it interactively, and
  230.         there seems to be no way to save code that was entered interactively.
  231.         How do I create a Python program on the Mac (PC)?
  232.  
  233. To find a particular question, search for the question number followed
  234. by a dot, a space, and a Q at the beginning of a line (e.g. to find
  235. question 4.2 in vi, type /^4\.2\. Q/).
  236.  
  237.  
  238. 1. General information and availability
  239.  =======================================
  240.  
  241. 1.1. Q. What is Python?
  242.  
  243. A. Python is an interpreted, interactive, object-oriented programming
  244. language.  It incorporates modules, exceptions, dynamic typing, very
  245. high level dynamic data types, and classes.  Python combines
  246. remarkable power with very clear syntax.  It has interfaces to many
  247. system calls and libraries, as well as to various window systems, and
  248. is extensible in C or C++.  It is also usable as an extension language
  249. for applications that need a programmable interface.  Finally, Python
  250. is portable: it runs on many brands of UNIX, on the Mac, and on PCs
  251. under MS-DOS, Windows, Windows NT, and OS/2.
  252.  
  253. To find out more, the best thing to do is to start reading the
  254. tutorial from the documentation set (see a few questions further
  255. down).
  256.  
  257. 1.2. Q. Why is it called Python?
  258.  
  259. A. Apart from being a computer scientist, I'm also a fan of "Monty
  260. Python's Flying Circus" (a BBC comedy series from the seventies, in
  261. the -- unlikely -- case you didn't know).  It occurred to me one day
  262. that I needed a name that was short, unique, and slightly mysterious.
  263. And I happened to be reading some scripts from the series at the
  264. time...  So then I decided to call my language Python.  But Python is
  265. not a joke.  And don't you associate it with dangerous reptiles
  266. either!  (If you need an icon, use an image of the 16-ton weight from
  267. the TV series or of a can of SPAM :-)
  268.  
  269. 1.3. Q. How do I obtain a copy of the Python source?
  270.  
  271. A. The latest complete Python source distribution is always available
  272. by anonymous ftp, e.g.
  273. <URL:ftp://ftp.python.org/pub/python/src/python1.3.tar.gz>.  It is a
  274. gzipped tar file containing the complete C source, LaTeX
  275. documentation, Python library modules, example programs, and several
  276. useful pieces of freely distributable software.  This will compile and
  277. run out of the box on most UNIX platforms.  (See section 7 for
  278. non-UNIX information.)
  279.  
  280. Sometimes beta versions of a newer release are available; check the
  281. subdirectory "beta" of the above-mentioned URL (i.e.
  282. <URL:ftp://ftp.python.org/pub/python/src/beta/>).  (At the time of
  283. writing, beta3 for Python 1.4 is available there, and should be
  284. checked before reporting problems with version 1.3.)
  285.  
  286. Occasionally a set of patches is issued which has to be applied using
  287. the patch program.  These patches are placed in the same directory,
  288. e.g. <URL:ftp://ftp.python.org/pub/python/src/patch1.1.1>.  (At the time
  289. of writing, no patches exist.)
  290.  
  291. An index of said ftp directory can be found in the file INDEX.  An
  292. HTML version of the index can be found in the file index.html,
  293. <URL:ftp://ftp.python.org/pub/python/index.html>.
  294.  
  295. 1.4. Q. How do I get documentation on Python?
  296.  
  297. A. The LaTeX source for the documentation is part of the source
  298. distribution.  If you don't have LaTeX, the latest Python
  299. documentation set is always available by anonymous ftp, e.g.
  300. <URL:ftp://ftp.python.org/pub/python/doc/postscript.tar.gz>.  It is a
  301. gzipped tar file containing PostScript files of the reference manual,
  302. the library manual, and the tutorial.  Note that the library manual is
  303. the most important one of the set, as much of Python's power stems
  304. from the standard or built-in types, functions and modules, all of
  305. which are described here.  PostScript for a high-level description of
  306. Python is in the file nluug-paper.ps (a separate file on the ftp
  307. site).
  308.  
  309. 1.5. Q. Are there other ftp sites that mirror the Python distribution?
  310.  
  311. A. The following anonymous ftp sites keep mirrors of the Python
  312. distribution:
  313.  
  314. USA:
  315.  
  316.         <URL:ftp://ftp.python.org/pub/python/>
  317.         <URL:ftp://gatekeeper.dec.com/pub/plan/python/>
  318.         <URL:ftp://ftp.uu.net/languages/python/>
  319.         <URL:ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/>
  320.         <URL:ftp://ftp.sterling.com/programming/languages/python/>
  321.         <URL:ftp://uiarchive.cso.uiuc.edu/pub/lang/python/>
  322.         <URL:ftp://ftp.pht.com/mirrors/python/python/>
  323.  
  324. Europe:
  325.  
  326.         <URL:ftp://ftp.cwi.nl/pub/python/>
  327.         <URL:ftp://ftp.funet.fi/pub/languages/python/>
  328.         <URL:ftp://ftp.sunet.se/pub/lang/python/>
  329.         <URL:ftp://unix.hensa.ac.uk/mirrors/uunet/languages/python/>
  330.         <URL:ftp://ftp.ibp.fr/pub/python/>
  331.         <URL:ftp://ftp.switch.ch/software/sources/python/>
  332.         <URL:ftp://ftp.informatik.tu-muenchen.de/pub/comp/programming/languages/python/>
  333.  
  334. Australia:
  335.  
  336.         <URL:ftp://ftp.dstc.edu.au/pub/python/>
  337.  
  338. Or try archie on the string "python".
  339.  
  340. 1.6. Q. Is there a newsgroup or mailing list devoted to Python?
  341.  
  342. A. There is a newsgroup, comp.lang.python <URL:news:comp.lang.python>,
  343. and a mailing list.  The newsgroup and mailing list are gatewayed into
  344. each other -- if you can read news it's unnecessary to subscribe to
  345. the mailing list.  Send e-mail to <python-list-request@cwi.nl> to
  346. (un)subscribe to the mailing list.  Hypermail archives of (nearly)
  347. everything posted to the mailing list (and thus the newsgroup) are
  348. available on our WWW server,
  349. <URL:http://www.cwi.nl/~guido/hypermail/index.html>.  The raw archives
  350. are also available by ftp, e.g.
  351. <URL:ftp://ftp.python.org/pub/python/mail/mailinglist.gz>.  The
  352. uncompressed versions of these files can be read with the standard
  353. UNIX Mail program ("Mail -f file") or with nn ("nn file").  To read
  354. them using MH, you could use "inc -file file".  (The archival service
  355. has stopped archiving new articles around the end of April 1995.  I
  356. hope to revive it on the PSA server www.python.org sometime in the
  357. future.)
  358.  
  359. 1.7. Q. Is there a WWW page devoted to Python?
  360.  
  361. A. Yes, <URL:http://www.python.org/> is the official Python home page.
  362. At the time of writing, this page is not yet completely operational;
  363. you may have a look at the old Python home page:
  364. <URL:http://www.cwi.nl/~guido/Python.html> or at the U.S. copy:
  365. <URL:http://www.python.org/~guido/Python.html>.
  366.  
  367. 1.8. Q. Is the Python documentation available on the WWW?
  368.  
  369. A. Yes, see <URL:http://www.python.org/> (Python's home page).  It
  370. contains pointers to hypertext versions of the whole documentation set
  371. (as hypertext, not just PostScript).
  372.  
  373. If you wish to browse this collection of HTML files on your own
  374. machine, it is available bundled up by anonymous ftp,
  375. e.g. <URL:ftp://ftp.python.org/pub/python/doc/html.tar.gz>.
  376.  
  377. An Emacs-INFO set containing the library manual is also available by
  378. ftp, e.g. <URL:ftp://ftp.python.org/pub/python/doc/lib-info.tar.gz>.
  379.  
  380. 1.9. Q. Is there a book on Python, or will there be one out soon?
  381.  
  382. A. Mark Lutz is writing a Python book for O'Reilly and Associates, to
  383. be published early 1996.  See the outline (in PostScript):
  384. <URL:http://www.python.org/workshops/1995-05/outlinep.eps>.
  385.  
  386. 1.10. Q. Are there any published articles about Python that I can quote?
  387.  
  388. A. So far the only refereed and published article that describes
  389. Python in some detail is:
  390.  
  391.     Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
  392.     Servers Using the Python Programming Language", CWI Quarterly, Volume
  393.     4, Issue 4 (December 1991), Amsterdam, pp 283-303.
  394.  
  395. LaTeX source for this paper is available as part of the Python source
  396. distribution.
  397.  
  398. See also the next section (supposedly Aaron Watters' paper has been
  399. refereed).
  400.  
  401. 1.11. Q. Are there short introductory papers or talks on Python?
  402.  
  403. A. A recent, very entertaining introduction to Python is the tutorial by
  404. Aaron Watters in UnixWorld Online:
  405.  
  406.     Aaron R. Watters: "The What, Why, Who, and Where of Python",
  407.     <URL:http://www.wcmh.com/uworld/archives/95/tutorial/005.html>
  408.  
  409. An olded paper is:
  410.  
  411.     Guido van Rossum, "An Introduction to Python for UNIX/C
  412.     Programmers", in the proceedings of the NLUUG najaarsconferentie
  413.     1993 (dutch UNIX users group meeting November 1993).
  414.  
  415. PostScript for this paper and for the slides used for the accompanying
  416. presentation is available by ftp as
  417. <URL:ftp://ftp.python.org/pub/python/doc/nluug-paper.ps> and
  418. <URL:ftp://ftp.python.org/pub/python/doc/nluug-slides.ps>, respectively.
  419.  
  420. Slides for a talk on Python that I gave at the Usenix Symposium on
  421. Very High Level Languages in Santa Fe, NM, USA in October 1994 are
  422. available as <URL:ftp://ftp.python.org/pub/python/doc/vhll-slides.ps>.
  423.  
  424. 1.12. Q. How does the Python version numbering scheme work?
  425.  
  426. A. Python versions are numbered A.B.C or A.B.  A is the major version
  427. number -- it is only incremented for major changes in functionality or
  428. source structure.  B is the minor version number, incremented for less
  429. earth-shattering changes to a release.  C is the patchlevel -- it is
  430. incremented for each new patch release.  Not all releases have patch
  431. releases.  Note that in the past, patches have added significant
  432. changes; in fact the changeover from 0.9.9 to 1.0.0 was the first time
  433. that either A or B changed!
  434.  
  435. Beta versions have an additional suffix of "betaN" for some small
  436. number N.  Note that (for instance) all versions labeled 1.4betaN
  437. *precede* the actual release of 1.4.  1.4b3 is short for 1.4beta3.
  438.  
  439. 1.13. Q. How do I get a beta test version of Python?
  440.  
  441. A. If there are any beta releases, they are published in the normal
  442. source directory (e.g. <URL:ftp://ftp.python.org/pub/python/src/>).
  443.  
  444. 1.14. Q. Are there copyright restrictions on the use of Python?
  445.  
  446. A. Hardly.  You can do anything you want with the source, as long as
  447. you leave the copyrights in, and display those copyrights in any
  448. documentation about Python that you produce.  Also, don't use the
  449. author's institute's name in publicity without prior written
  450. permission, and don't hold them responsible for anything (read the
  451. actual copyright for a precise legal wording).
  452.  
  453. In particular, if you honor the copyright rules, it's OK to use Python
  454. for commercial use, to sell copies of Python in source or binary form,
  455. or to sell products that enhance Python or incorporate Python (or part
  456. of it) in some form.  I would still like to know about all commercial
  457. use of Python!
  458.  
  459. 1.15. Q. Why was Python created in the first place?
  460.  
  461. A. Here's a *very* brief summary of what got me started:
  462.  
  463. - I had extensive experience with implementing an interpreted language
  464. in the ABC group at CWI, and from working with this group I had
  465. learned a lot about language design.  This is the origin of many
  466. Python features, including the use of indentation for statement
  467. grouping and the inclusion of very-high-level data types (although the
  468. details are all different in Python).
  469.  
  470. - I had a number of gripes about the ABC language, but also liked many
  471. of its features.  It was impossible to extend the ABC language (or its
  472. implementation) to remedy my complaints -- in fact its lack of
  473. extensibility was one of its biggest problems.
  474.  
  475. - I had some experience with using Modula-2+ and talked with the
  476. designers of Modula-3 (and read the M3 report).  M3 is the origin of
  477. the syntax and semantics used for exceptions, and some other Python
  478. features.
  479.  
  480. - I was working in the Amoeba distributed operating system group at
  481. CWI.  We needed a better way to do system administration than by
  482. writing either C programs or Bourne shell scripts, since Amoeba had
  483. its own system call interface which wasn't easily accessible from the
  484. Bourne shell.  My experience with error handling in Amoeba made me
  485. acutely aware of the importance of exceptions as a programming
  486. language feature.
  487.  
  488. - It occurred to me that a scripting language with a syntax like ABC
  489. but with access to the Amoeba system calls would fill the need.  I
  490. realized that it would be foolish to write an Amoeba-specific
  491. language, so I decided that I needed a language that was generally
  492. extensible.
  493.  
  494. - During the 1989 Christmas holidays, I had a lot of time on my hand,
  495. so I decided to give it a try.  During the next year, while still
  496. mostly working on it in my own time, Python was used in the Amoeba
  497. project with increasing success, and the feedback from colleagues made
  498. me add many early improvements.
  499.  
  500. - In February 1991, after just over a year of development, I decided
  501. to post to USENET.  The rest is in the Misc/HISTORY file.
  502.  
  503.  
  504. 2. Python in the real world
  505. ===========================
  506.  
  507. 2.1. Q. How many people are using Python?
  508.  
  509. A. I don't know, but the maximum number of simultaneous subscriptions
  510. to the Python mailing list before it was gatewayed into the newsgroup
  511. was about 180 (several of which were local redistribution lists).  I
  512. believe that many active Python users don't bother to subscribe to the
  513. list, and now that there's a newsgroup the mailing list subscription
  514. is even less meaningful.  I see new names on the newsgroup all the
  515. time and my best guess is that there are currently at least several
  516. thousands of users.
  517.  
  518. Another statistic is the number of accesses to the Python WWW server.
  519. Have a look at <URL:http://www.python.org/stats/>.
  520.  
  521. 2.2. Q. Have any significant projects been done in Python?
  522.  
  523. A. Here at CWI (the home of Python), we have written a 20,000 line
  524. authoring environment for transportable hypermedia presentations, a
  525. 5,000 line multimedia teleconferencing tool, as well as many many
  526. smaller programs.
  527.  
  528. The University of Virginia uses Python to control a virtual reality
  529. engine.  Contact: Matt Conway <conway@virginia.edu>.
  530.  
  531. The ILU project at Xerox PARC can generate Python glue for ILU
  532. interfaces.  See <URL:ftp://ftp.parc.xerox.com/pub/ilu/ilu.html>.
  533.  
  534. The University of California, Irvine uses a student administration
  535. system called TELE-Vision written entirely in Python.  Contact: Ray
  536. Price <rlprice@uci.edu>.
  537.  
  538. See also the next question.
  539.  
  540. If you have done a significant project in Python that you'd like to be
  541. included in the list above, send me email!
  542.  
  543. 2.3. Q. Are there any commercial projects going on using Python?
  544.  
  545. A. Several companies have revealed to me that they are planning or
  546. considering use of Python in a future product.
  547.  
  548. Sunrise Software has a product out using Python -- they use Python
  549. for a GUI management application and an SNMP network management
  550. application.  Contact: <info@sunrise.com>.
  551.  
  552. Infoseek uses Python to implement their commercial WWW information
  553. retrieval service <URL:http://www.infoseek.com/>.  Contact:
  554. <info@infoseek.com>.
  555.  
  556. Paul Everitt of Connecting Minds is planning a Lotus Notes gateway.
  557. Contact: <Paul.Everitt@cminds.com>.  Or see their WWW server
  558. <URL:http://www.cminds.com/>.
  559.  
  560. KaPRE in Boulder, CO is using Python for on-site customization of C++
  561. applications, rapid-prototyping/development,
  562. language-based-components, and possibly more.  This is pretty solid:
  563. Python's being shipped with their tool-set now, to beta sites.
  564. Contact: <lutz@KaPRE.COM> (Mark Lutz).
  565.  
  566. Individuals at many other companies are using Python for internal
  567. development or for as yet unannounced products (witness their
  568. contributions to the Python mailing list or newsgroup).
  569.  
  570. SGI has advertised in the Python list looking for Python programmers
  571. for a project involving interactive television.
  572.  
  573. See also the workshop minutes at
  574. <URL:http://www.python.org/workshops/> -- in general the WWW server is
  575. more up to date than the FAQ for these issues.
  576.  
  577. Python has also been elected as an extension language by MADE, a
  578. consortium supported by the European Committee's ESPRIT program and
  579. consisting of Bull, CWI and some other European companies.  Contact:
  580. Ivan Herman <ivan@cwi.nl>.
  581.  
  582. If you'd like to be included in the list above, send me email!
  583.  
  584. 2.4. Q. How stable is Python?
  585.  
  586. A. Very stable.  While the current version number would suggest it is
  587. in the early stages of development, in fact new, stable releases
  588. (numbered 0.9.x through 1.3) have been coming out roughly every 3 to
  589. 6 months for the past four years.
  590.  
  591. 2.5. Q. What new developments are expected for Python in the future?
  592.  
  593. A. See my Work-In-Progress web page, currently at
  594. <URL:http://www.python.org:~guido/WIP.html>, and the pages for the
  595. Second Python Workshop (best reached via the Python home page,
  596. <URL:http://www.python.org/>).  Also follow the newsgroup discussions!
  597.  
  598. 2.6. Q. Is it reasonable to propose incompatible changes to Python?
  599.  
  600. A. In general, no.  There are already millions of lines of Python code
  601. around the world, so any changes in the language that invalidates more
  602. than a very small fraction of existing programs has to be frowned
  603. upon.  Even if you can provide a conversion program, there still is
  604. the problem of updating all documentation.  Providing a gradual
  605. upgrade path is the only way if a feature has to be changed.
  606.  
  607. 2.7. Q. What is the future of Python?
  608.  
  609. A. If I knew, I'd be rich :-)
  610.  
  611. Seriously, the formation of the PSA (Pyton Software Activity, see
  612. <URL:http://www.python.org/psa/>) ensures some kind of support even in
  613. the (unlikely! event that I'd be hit by a bus (actually, here in the
  614. US, a car accident would be more likely :-), were to join a nunnery,
  615. or would be head-hunted.  A large number of Python users have become
  616. experts at Python programming as well as maintenance of the
  617. implementation, and would easily fill the vacuum created by my
  618. disappearance.
  619.  
  620. In the mean time, I have no plans to disappear -- rather, I am
  621. committed to improving Python, and my current benefactor, CNRI (see
  622. <URL:http://www.cnri.reston.va.us>) is just as committed to continue
  623. its support of Python and the PSA.  In fact, we have great plans for
  624. Python -- we just can't tell yet!
  625.  
  626. 2.8. Q. What is the PSA, anyway?
  627.  
  628. A. The Python Software Activity <URL:http://www.python.org/psa/> was
  629. created by a number of Python aficionados who want Python to be more
  630. than the product and responsibility of a single individual.  It has
  631. found a home at CNRI <URL:http://www.cnri.reston.va.us>.  Anybody who
  632. wishes Python well should join the PSA.
  633.  
  634. 2.9. Q. How do I join the PSA?
  635.  
  636. A. The full scoop is available on the web, see
  637. <URL:http://www.python.org/psa/Joining.html>.  Summary: send a check
  638. of at least $50 to CNRI/PSA, 1895 Preston White Drive, Suite 100, in
  639. Reston, VA 20191.  Full-time students pay $25.  Companies can join for
  640. a mere $500.
  641.  
  642. 2.10. Q. What are the benefits of joining the PSA?
  643.  
  644. A. Like National Public Radio, if not enough people join, Python will
  645. wither.  Your name will be mentioned on the PSA's web server.
  646. Workshops organized by the PSA <URL:http://www.python.org/workshops/>
  647. are only accessible to PSA members (you can join at the door).  The
  648. PSA is working on additional benefits, such as reduced prices for
  649. books and software, and early access to beta versions of Python.
  650.  
  651.  
  652. 3. Building Python and Other Known Bugs
  653. =======================================
  654.  
  655. 3.1. Q. Is there a test set?
  656.  
  657. A. Yes, simply do "import testall" (or "import autotest" if you aren't
  658. interested in the output).  The standard modules whose name begins
  659. with "test" together comprise the test.  The test set doesn't test
  660. *all* features of Python but it goes a long way to confirm that a new
  661. port is actually working.  The Makefile contains an entry "make test"
  662. which runs the autotest module.  NOTE: if "make test" fails, run the
  663. tests manually ("import testall") to see what goes wrong before
  664. reporting the error.
  665.  
  666. 3.2. Q. When running the test set, I get complaints about floating point
  667. operations, but when playing with floating point operations I cannot
  668. find anything wrong with them.
  669.  
  670. A. The test set makes occasional unwarranted assumptions about the
  671. semantics of C floating point operations.  Until someone donates a
  672. better floating point test set, you will have to comment out the
  673. offending floating point tests and execute similar tests manually.
  674.  
  675. 3.3. Q. Link errors after rerunning the configure script.
  676.  
  677. A. It is generally necessary to run "make clean" after a configuration
  678. change.
  679.  
  680. 3.4. Q. The python interpreter complains about options passed to a
  681. script (after the script name).
  682.  
  683. A. You are probably linking with GNU getopt, e.g. through -liberty.
  684. Don't.  The reason for the complaint is that GNU getopt, unlike System
  685. V getopt and other getopt implementations, doesn't consider a
  686. non-option to be the end of the option list.  A quick (and compatible)
  687. fix for scripts is to add "--" to the interpreter, like this:
  688.  
  689.         #! /usr/local/bin/python --
  690.  
  691. You can also use this interactively:
  692.  
  693.         python -- script.py [options]
  694.  
  695. Note that a working getopt implementation is provided in the Python
  696. distribution (in Python/getopt.c) but not automatically used.
  697.  
  698. 3.5. Q. When building on the SGI, make tries to run python to create
  699. glmodule.c, but python hasn't been built or installed yet.
  700.  
  701. A. Comment out the line mentioning glmodule.c in Setup and build a
  702. python without gl first; install it or make sure it is in your $PATH,
  703. then edit the Setup file again to turn on the gl module, and make
  704. again.  You don't need to do "make clean"; you do need to run "make
  705. Makefile" in the Modules subdirectory (or just run "make" at the
  706. toplevel).
  707.  
  708. 3.6. Q. I use VPATH but some targets are built in the source directory.
  709.  
  710. A. On some systems (e.g. Sun), if the target already exists in the
  711. source directory, it is created there instead of in the build
  712. directory.  This is usually because you have previously built without
  713. VPATH.  Try running "make clobber" in the source directory.
  714.  
  715. 3.7. Q. Trouble building or linking with the GNU readline library.
  716.  
  717. A. Consider using readline 2.0.  Some hints:
  718.  
  719. - You can use the GNU readline library to improve the interactive user
  720. interface: this gives you line editing and command history when
  721. calling python interactively. You need to configure and build the GNU
  722. readline library before running the configure script. Its sources are
  723. no longer distributed with Python; you can ftp them from any GNU
  724. mirror site, or from its home site
  725. <URL:ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz> (or a
  726. higher version number -- using version 1.x is not recommended). Pass
  727. the Python configure script the option --with-readline=DIRECTORY where
  728. DIRECTORY is the absolute pathname of the directory where you've built
  729. the readline library. Some hints on building and using the readline
  730. library:
  731.  
  732. - On SGI IRIX 5, you may have to add the following
  733. to rldefs.h:
  734.  
  735.         #ifndef sigmask
  736.         #define sigmask(sig) (1L << ((sig)-1))
  737.         #endif
  738.  
  739. - On most systems, you will have to add #include "rldefs.h" to the
  740. top of several source files, and if you use the VPATH feature, you
  741. will have to add dependencies of the form foo.o: foo.c to the
  742. Makefile for several values of foo.
  743.  
  744. - The readline library requires use of the termcap library. A
  745. known problem with this is that it contains entry points which
  746. cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
  747. conflict can be solved (and will be, in the next release of
  748. STDWIN) by adding a line saying '#define werase w_erase' to the
  749. stdwin.h file (in the STDWIN distribution, subdirectory H). The
  750. GL conflict has been solved in the Python configure script by a
  751. hack that forces use of the static version of the termcap library.
  752.  
  753. - Check the newsgroup gnu.bash.bug <URL:news:gnu.bash.bug> for
  754. specific problems with the readline library (I don't read this group
  755. but I've been told that it is the place for readline bugs).
  756.  
  757. 3.8. Q. Trouble with socket I/O on older Linux 1.x versions.
  758.  
  759. A. Once you've built Python, use it to run the regen.py script in the
  760. Lib/linux1 directory.  Apparently the files as distributed don't match
  761. the system headers on some Linux versions.
  762.  
  763. 3.9. Q. Trouble with prototypes on Ultrix.
  764.  
  765. A. Ultrix cc seems broken -- use gcc, or edit config.h to #undef
  766. HAVE_PROTOTYPES.
  767.  
  768. 3.10. Q. Other trouble building Python on platform X.
  769.  
  770. A. Please email the details to <guido@cnri.reston.va.us> and I'll look
  771. into it.  Please provide as many details as possible.  In particular,
  772. if you don't tell me what type of computer and what operating system
  773. (and version) you are using it will be difficult for me to figure out
  774. what is the matter.  If you get a specific error message, please email
  775. it to me too.
  776.  
  777. 3.11. Q. How to configure dynamic loading on Linux.
  778.  
  779. A. This is now automatic as long as your Linux version uses the ELF
  780. object format (all recent Linuxes do).
  781.  
  782. 3.12. Q: I can't get shared modules to work on Linux 2.0 (Slackware96)?
  783.  
  784. A: This is a bug in the Slackware96 release.   The fix is simple:
  785.  
  786. Make sure that there is a link from /lib/libdl.so to /lib/libdl.so.1
  787. so that the following links are setup:
  788.  
  789.     /lib/libdl.so -> /lib/libdl.so.1
  790.     /lib/libdl.so.1 -> /lib/libdl.so.1.7.14
  791.  
  792. 3.13. Q. How to use threads on Linux.
  793.  
  794. A. [Greg Stein] I built myself a libpthreads.so from the libc.5.3.12
  795. distribution (the binary distribution doesn't have pthreads in
  796. it).  Then, I configured Python with --with-threads and then tweaked
  797. config.h to include a #define _MIT_POSIX_THREADS (or something like
  798. that, see /usr/include/pthreads.h).  It worked fine at that point.
  799.  
  800. Note that I couldn't get threading to "operate well" with any of the
  801. other thread packages.  Prior libc versions didn't integrate well with
  802. threads, either, so I couldn't use them (e.g. sleep() blocked all
  803. threads :-( ).
  804.  
  805. 3.14. Q. Errors when linking with a shared library containing C++ code.
  806.  
  807. A. Link the main Python binary with C++.  Change the definition of
  808. LINKCC in Modules/Makefile to be your C++ compiler.  You may have to
  809. edit config.c slightly to make it compilable with C++.
  810.  
  811. 3.15. Q. I built with tkintermodule.c enabled but get "Tkinter not found".
  812.  
  813. A. Tkinter.py (note: upper case T) lives in a subdirectory of Lib,
  814. Lib/tkinter.  If you are using the default module search path, you
  815. probably didn't enable the line in the Modules/Setup file defining
  816. TKPATH; if you use the environment variable PYTHONPATH, you'll have to
  817. add  the proper tkinter subdirectory.
  818.  
  819. 3.16. Q. I built with Tk 4.0 but Tkinter complains about the Tk version.
  820.  
  821. A. Several things could cause this.  You most likely have a Tk 3.6
  822. installation that wasn't completely eradicated by the Tk 4.0
  823. installation (which tends to add "4.0" to its installed files).  You
  824. may have the Tk 3.6 support library installed in the place where the
  825. Tk 4.0 support files should be (default /usr/local/lib/tk/); you may
  826. have compiled Python with the old tk.h header file (yes, this actually
  827. compiles!); you may actually have linked with Tk 3.6 even though Tk
  828. 4.0 is also around.  Similar for Tcl 7.4 vs. Tcl 7.3.
  829.  
  830. 3.17. Q. Link errors for Tcl/Tk symbols when linking with Tcl/Tk.
  831.  
  832. Quite possibly, there's a version mismatch between the Tcl/Tk header
  833. files (tcl.h and tk.h) and the tck/tk libraries you are using (the
  834. "-ltk4.0" and "-ltcl7.4" arguments for _tkinter in the Setup file).
  835. If you have installed both versions 7.4/4.0 and 7.5/4.1 of Tcl/Tk,
  836. most likely your header files are for The newer versions, but the
  837. Setup line for _tkinter in some Python distributions references
  838. 7.4/4.0 by default.  Changing this to 7.5/4.1 should take care of
  839. this.
  840.  
  841. 3.18. Q. I configured and built Python for Tcl/Tk but "import Tkinter"
  842. fails.
  843.  
  844. A. Most likely, you forgot to enable the line in Setup that says
  845. "TKPATH=:$(DESTLIB)/tkinter".
  846.  
  847. 3.19. Q. Tk doesn't work right on DEC Alpha.
  848.  
  849. A. You probably compiled either Tcl, Tk or Python with gcc.  Don't.
  850. For this platform, which has 64-bit integers, gcc is known to generate
  851. broken code.  The standard cc (which comes bundled with the OS!)
  852. works.  If you still prefer gcc, at least try recompiling with cc
  853. before reporting problems to the newsgroup or the author; if this
  854. fixes the problem, report the bug to the gcc developers instead.  (As
  855. far as we know, there are no problem with gcc on other platforms --
  856. the instabilities seem to be restricted to the DEC Alpha.)  See also
  857. question 3.6.
  858.  
  859. 3.20. Q. Several common system calls are missing from the posix module.
  860.  
  861. A. Most likely, *all* test compilations run by the configure script
  862. are failing for some reason or another.  Have a look in config.log to
  863. see what could be the reason.  A common reason is specifying a
  864. directory to the --with-readline option that doesn't contain the
  865. libreadline.a file.
  866.  
  867. 3.21. Q. ImportError: No module named string, on MS Windows.
  868.  
  869. A. Most likely, your PYTHONPATH environment variable should be set to
  870. something like:
  871.  
  872. set PYTHONPATH=c:\python;c:\python\lib;c:\python\scripts
  873.  
  874. (assuming Python was installed in c:\python)
  875.  
  876. 3.22. Q. Core dump on SGI when using the gl module.
  877.  
  878. There are conflicts between entry points in the termcap and curses
  879. libraries and an entry point in the GL library.  There's a hack of a
  880. fix for the termcap library if it's needed for the GNU readline
  881. library, but it doesn't work when you're using curses.  Concluding,
  882. you can't build a Python binary containing both the curses and gl
  883. modules.
  884.  
  885.  
  886.  
  887. 4. Programming in Python
  888. ========================
  889.  
  890. 4.1. Q. Is there a source code level debugger with breakpoints, step,
  891. etc.?
  892.  
  893. A. Yes.  Check out module pdb; pdb.help() prints the documentation (or
  894. you can read it as Lib/pdb.doc).  If you use the STDWIN option,
  895. there's also a windowing interface, wdb.  You can write your own
  896. debugger by using the code for pdb or wdb as an example.
  897.  
  898. 4.2. Q. Can I create an object class with some methods implemented in
  899. C and others in Python (e.g. through inheritance)?  (Also phrased as:
  900. Can I use a built-in type as base class?)
  901.  
  902. A. No, but you can easily create a Python class which serves as a
  903. wrapper around a built-in object, e.g. (for dictionaries):
  904.  
  905.         # A user-defined class behaving almost identical
  906.         # to a built-in dictionary.
  907.         class UserDict:
  908.                 def __init__(self): self.data = {}
  909.                 def __repr__(self): return repr(self.data)
  910.                 def __cmp__(self, dict):
  911.                         if type(dict) == type(self.data):
  912.                                 return cmp(self.data, dict)
  913.                         else:
  914.                                 return cmp(self.data, dict.data)
  915.                 def __len__(self): return len(self.data)
  916.                 def __getitem__(self, key): return self.data[key]
  917.                 def __setitem__(self, key, item): self.data[key] = item
  918.                 def __delitem__(self, key): del self.data[key]
  919.                 def keys(self): return self.data.keys()
  920.                 def items(self): return self.data.items()
  921.                 def values(self): return self.data.values()
  922.                 def has_key(self, key): return self.data.has_key(key)
  923.  
  924. 4.3. Q. Is there a curses/termcap package for Python?
  925.  
  926. A. Yes -- Lance Ellinghaus has written a module that interfaces to
  927. System V's "ncurses".  If you know a little curses and some Python,
  928. it's straightforward to use.  It is part of the standard Python
  929. distribution, but not configured by default -- you must enable it by
  930. editing Modules/Setup.  It requires a System V curses implementation.
  931.  
  932. You could also consider using the "alfa" (== character cell) version
  933. of STDWIN.  (Standard Window System Interface, a portable windowing
  934. system interface by myself <URL:ftp://ftp.cwi.nl/pub/stdwin/>.)  This
  935. will also prepare your program for porting to windowing environments
  936. such as X11 or the Macintosh.
  937.  
  938. 4.4. Q. Is there an equivalent to C's onexit() in Python?
  939.  
  940. A. Yes, if you import sys and assign a function to sys.exitfunc, it
  941. will be called when your program exits, is killed by an unhandled
  942. exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
  943.  
  944. 4.5. Q. When I define a function nested inside another function, the
  945. nested function seemingly can't access the local variables of the
  946. outer function.  What is going on?  How do I pass local data to a
  947. nested function?
  948.  
  949. A. Python does not have arbitrarily nested scopes.  When you need to
  950. create a function that needs to access some data which you have
  951. available locally, create a new class to hold the data and return a
  952. method of an instance of that class, e.g.:
  953.  
  954.         class MultiplierClass:
  955.             def __init__(self, factor):
  956.                 self.factor = factor
  957.             def multiplier(self, argument):
  958.                 return argument * self.factor
  959.  
  960.         def generate_multiplier(factor):
  961.             return MultiplierClass(factor).multiplier
  962.  
  963.         twice = generate_multiplier(2)
  964.         print twice(10)
  965.         # Output: 20
  966.  
  967. An alternative solution uses default arguments, e.g.:
  968.  
  969.         def generate_multiplier(factor):
  970.             def multiplier(arg, fact = factor):
  971.                 return arg*fact
  972.             return multiplier
  973.  
  974.         twice = generate_multiplier(2)
  975.         print twice(10)
  976.         # Output: 20
  977.  
  978. 4.6. Q. How do I iterate over a sequence in reverse order?
  979.  
  980. A. If it is a list, the fastest solution is
  981.  
  982.         list.reverse()
  983.         try:
  984.                 for x in list:
  985.                         "do something with x"
  986.         finally:
  987.                 list.reverse()
  988.  
  989. This has the disadvantage that while you are in the loop, the list
  990. is temporarily reversed.  If you don't like this, you can make a copy.
  991. This appears expensive but is actually faster than other solutions:
  992.  
  993.         rev = list[:]
  994.         rev.reverse()
  995.         for x in rev:
  996.                 <do something with x>
  997.  
  998. If it isn't a list, a more general but slower solution is:
  999.  
  1000.         i = len(list)
  1001.         while i > 0:
  1002.                 i = i-1
  1003.                 x = list[i]
  1004.                 <do something with x>
  1005.  
  1006. A more elegant solution, is to define a class which acts as a sequence
  1007. and yields the elements in reverse order (solution due to Steve
  1008. Majewski):
  1009.  
  1010.         class Rev:
  1011.                 def __init__(self, seq):
  1012.                         self.forw = seq
  1013.                 def __len__(self):
  1014.                         return len(self.forw)
  1015.                 def __getitem__(self, i):
  1016.                         return self.forw[-(i + 1)]
  1017.  
  1018. You can now simply write:
  1019.  
  1020.         for x in Rev(list):
  1021.                 <do something with x>
  1022.  
  1023. Unfortunately, this solution is slowest of all, due to the method
  1024. call overhead...
  1025.  
  1026. 4.7. Q. My program is too slow.  How do I speed it up?
  1027.  
  1028. A. That's a tough one, in general.  There are many tricks to speed up
  1029. Python code; I would consider rewriting parts in C only as a last
  1030. resort.  One thing to notice is that function and (especially) method
  1031. calls are rather expensive; if you have designed a purely OO interface
  1032. with lots of tiny functions that don't do much more than get or set an
  1033. instance variable or call another method, you may consider using a
  1034. more direct way, e.g. directly accessing instance variables.  Also see
  1035. the standard module "profile" (described in the file
  1036. "python/lib/profile.doc") which makes it possible to find out where
  1037. your program is spending most of its time (if you have some patience
  1038. -- the profiling itself can slow your program down by an order of
  1039. magnitude).
  1040.  
  1041. 4.8. Q. When I have imported a module, then edit it, and import it
  1042. again (into the same Python process), the changes don't seem to take
  1043. place.  What is going on?
  1044.  
  1045. A. For reasons of efficiency as well as consistency, Python only reads
  1046. the module file on the first time a module is imported.  (Otherwise a
  1047. program consisting of many modules, each of which imports the same
  1048. basic module, would read the basic module over and over again.)  To
  1049. force rereading of a changed module, do this:
  1050.  
  1051.         import modname
  1052.         reload(modname)
  1053.  
  1054. Warning: this technique is not 100% fool-proof.  In particular,
  1055. modules containing statements like
  1056.  
  1057.         from modname import some_objects
  1058.  
  1059. will continue to work with the old version of the imported objects.
  1060.  
  1061. 4.9. Q. How do I find the current module name?
  1062.  
  1063. A. A module can find out its own module name by looking at the
  1064. (predefined) global variable __name__.  If this has the value
  1065. '__main__' you are running as a script.  
  1066.  
  1067. 4.10. Q. I have a module in which I want to execute some extra code
  1068. when it is run as a script.  How do I find out whether I am running as
  1069. a script?
  1070.  
  1071. A. See the previous question.  E.g. if you put the following on the
  1072. last line of your module, main() is called only when your module is
  1073. running as a script:
  1074.  
  1075.         if __name__ == '__main__': main()
  1076.  
  1077. 4.11. Q. I try to run a program from the Demo directory but it fails
  1078. with ImportError: No module named ...; what gives?
  1079.  
  1080. A. This is probably an optional module (written in C!) which hasn't
  1081. been configured on your system.  This especially happens with modules
  1082. like "Tkinter", "stdwin", "gl", "Xt" or "Xm".  For Tkinter, STDWIN and
  1083. many other modules, see Modules/Setup.in for info on how to add these
  1084. modules to your Python, if it is possible at all.  Sometimes you will
  1085. have to ftp and build another package first (e.g. STDWIN).  Sometimes
  1086. the module only works on specific platforms (e.g. gl only works on SGI
  1087. machines).
  1088.  
  1089. NOTE: if the complaint is about "Tkinter" (upper case T) and you have
  1090. already configured module "tkinter" (lower case t), the solution is
  1091. *not* to rename tkinter to Tkinter or vice versa.  There is probably
  1092. something wrong with your module search path.  Check out the value of
  1093. sys.path.
  1094.  
  1095. For X-related modules (Xt and Xm) you will have to do more work: they
  1096. are currently not part of the standard Python distribution.  You will
  1097. have to ftp the Extensions tar file, e.g.
  1098. <URL:ftp://ftp.python.org/pub/python/src/extensions.tar.gz> and follow
  1099. the instructions there.
  1100.  
  1101. See also the next question.
  1102.  
  1103. 4.12. Q. I have successfully built Python with STDWIN but it can't
  1104. find some modules (e.g. stdwinevents).
  1105.  
  1106. A. There's a subdirectory of the library directory named 'stdwin'
  1107. which should be in the default module search path.  There's a line in
  1108. Modules/Setup(.in) that you have to enable for this purpose --
  1109. unfortunately in the latest release it's not near the other
  1110. STDWIN-related lines so it's easy to miss it.
  1111.  
  1112. 4.13. Q. What GUI toolkits exist for Python?
  1113.  
  1114. A. Depending on what platform(s) you are aiming at, there are several.
  1115.  
  1116. Currently supported solutions:
  1117.  
  1118. - There's a neat object-oriented interface to the Tcl/Tk widget set,
  1119. called Tkinter.  It is part of the standard Python distribution and
  1120. well-supported -- all you need to do is build and install Tcl/Tk and
  1121. enable the _tkinter module and the TKPATH definition in Modules/Setup
  1122. when building Python.  This is probably the easiest to install and
  1123. use, and the most complete widget set.  It is also very likely that in
  1124. the future the standard Python GUI API will be based on or at least
  1125. look very much like the Tkinter interface.  For more info about Tk,
  1126. including pointers to the source, see the Tcl/Tk home page
  1127. <URL:http://www.sunlabs.com/research/tcl/>.  Tcl/Tk is now fully
  1128. portable to the Mac and Windows platforms (NT and 95 only); you need
  1129. Python 1.4beta3 or later and Tk 4.1patch1 or later.
  1130.  
  1131. - There's an interface to X11, including the Athena and Motif widget
  1132. sets (and a few individual widgets, like Mosaic's HTML widget and
  1133. SGI's GL widget) available from
  1134. <URL:ftp://ftp.python.org/pub/python/src/X-extension.tar.gz>.
  1135. Support by Sjoerd Mullender <sjoerd@cwi.nl>.
  1136.  
  1137. - On top of the X11 interface there's the (recently revived) vpApp
  1138. toolkit by Per Spilling, now also maintained by Sjoerd Mullender
  1139. <sjoerd@cwi.nl>.  See <URL:ftp://ftp.cwi.nl/pub/sjoerd/vpApp.tar.gz>.
  1140.  
  1141. - The Mac port has a rich and ever-growing set of modules that support
  1142. the native Mac toolbox calls.  See the documentation that comes with
  1143. the Mac port.  See <URL:ftp://ftp.python.org/pub/python/mac>.  Support
  1144. by Jack Jansen <jack@cwi.nl>.
  1145.  
  1146. - The NT port supported by Mark Hammond <MHammond@skippinet.com.au>
  1147. (see question 7.2) includes an interface to the Microsoft Foundation
  1148. Classes and a Python programming environment using it that's written
  1149. mostly in Python.  See
  1150. <URL:ftp://ftp.python.org/pub/python/pythonwin/>.
  1151.  
  1152. - There's an object-oriented GUI based on the Microsoft Foundation
  1153. Classes model called WPY, supported by Jim Ahlstrom <jim@interet.com>.
  1154. Programs written in WPY run unchanged and with native look and feel on
  1155. Windows NT/95, Windows 3.1 (using win32s), and on Unix (using Tk).
  1156. Source and binaries for Windows and Linux are available in
  1157. <URL:ftp://ftp.python.org/pub/python/wpy/>.
  1158.  
  1159. Obsolete or minority solutions:
  1160.  
  1161. - There's an interface to wxWindows.  wxWindows is a portable GUI
  1162. class library written in C++.  It supports XView, Motif, MS-Windows as
  1163. targets.  There is some support for Macs and CURSES as well.
  1164. wxWindows preserves the look and feel of the underlying graphics
  1165. toolkit.  See the wxPython WWW page at
  1166. <URL:http://www.aiai.ed.ac.uk/~jacs/wx/wxpython/wxpython.html>.
  1167. Support for wxPython (by Harri Pasanen <pa@tekla.fi>) appears
  1168. to have a low priority.
  1169.  
  1170. - For SGI IRIX only, there are unsupported interfaces to the complete
  1171. GL (Graphics Library -- low level but very good 3D capabilities) as
  1172. well as to FORMS (a buttons-and-sliders-etc package built on top of GL
  1173. by Mark Overmars -- ftp'able from
  1174. <URL:ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/>).  This is probably also
  1175. becoming obsolete, as OpenGL takes over.
  1176.  
  1177. - There's an interface to STDWIN, a platform-independent low-level
  1178. windowing interface for Mac and X11.  This is totally unsupported and
  1179. rapidly becoming obsolete.  The STDWIN sources are at
  1180. <URL:ftp://ftp.cwi.nl/pub/stdwin/>.  (For info about STDWIN 2.0,
  1181. please refer to Steven Pemberton <steven@cwi.nl> -- I believe it is
  1182. also dead.)
  1183.  
  1184. - There once was an interface to WAFE, a Tcl interface to the X11
  1185. Motif and Athena widget sets.  WAFE is at
  1186. <URL:ftp://ftp.wu-wien.ac.at/pub/src/X11/wafe/>.  It's not clear what
  1187. the status of the Python support is.
  1188.  
  1189. - (The Fresco port that was mentioned in earlier versions of this FAQ
  1190. no longer seems to exist.  Inquire with Mark Linton.)
  1191.  
  1192. 4.14. Q. Are there any interfaces to database packages in Python?
  1193.  
  1194. A. There's a whole collection of them in the contrib area of the ftp
  1195. server, see <URL:http://www.python.org/ftp/python/contrib/Database/>.
  1196.  
  1197. 4.15. Q. Is it possible to write obfuscated one-liners in Python?
  1198.  
  1199. A. Yes.  See the following three examples, due to Ulf Bartelt:
  1200.  
  1201.         # Primes < 1000
  1202.         print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
  1203.         map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
  1204.  
  1205.         # First 10 Fibonacci numbers
  1206.         print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
  1207.         range(10))
  1208.  
  1209.         # Mandelbrot set
  1210.         print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
  1211.         Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
  1212.         Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
  1213.         i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
  1214.         >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
  1215.         64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
  1216.         ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
  1217.         #    \___ ___/  \___ ___/  |   |   |__ lines on screen
  1218.         #        V          V      |   |______ columns on screen
  1219.         #        |          |      |__________ maximum of "iterations"
  1220.         #        |          |_________________ range on y axis
  1221.         #        |____________________________ range on x axis
  1222.  
  1223. Don't try this at home, kids!
  1224.  
  1225. 4.16. Q. Is there an equivalent of C's "?:" ternary operator?
  1226.  
  1227. A. Not directly.  In many cases you can mimic a?b:c with "a and b or
  1228. c", but there's a flaw: if b is zero (or empty, or None -- anything
  1229. that tests false) then c will be selected instead.  In many cases you
  1230. can prove by looking at the code that this can't happen (e.g. because
  1231. b is a constant or has a type that can never be false), but in general
  1232. this can be a problem.
  1233.  
  1234. Tim Peters (who wishes it was Steve Majewski) suggested the following
  1235. solution: (a and [b] or [c])[0].  Because [b] is a singleton list it
  1236. is never false, so the wrong path is never taken; then applying [0] to
  1237. the whole thing gets the b or c that you really wanted.  Ugly, but it
  1238. gets you there in the rare cases where it is really inconvenient to
  1239. rewrite your code using 'if'.
  1240.  
  1241. 4.17. Q. My class defines __del__ but it is not called when I delete the
  1242. object.
  1243.  
  1244. A. There are several possible reasons for this.
  1245.  
  1246. - The del statement does not necessarily call __del__ -- it simply
  1247. decrements the object's reference count, and if this reaches zero
  1248. __del__ is called.
  1249.  
  1250. - If your data structures contain circular links (e.g. a tree where
  1251. each child has a parent pointer and each parent has a list of
  1252. children) the reference counts will never go back to zero.  You'll
  1253. have to define an explicit close() method which removes those
  1254. pointers.  Please don't ever call __del__ directly -- __del__ should
  1255. call close() and close() should make sure that it can be called more
  1256. than once for the same object.
  1257.  
  1258. - If the object has ever been a local variable (or argument, which is
  1259. really the same thing) to a function that caught an expression in an
  1260. except clause, chances are that a reference to the object still exists
  1261. in that function's stack frame as contained in the stack trace.
  1262. Normally, deleting (better: assigning None to) sys.exc_traceback will
  1263. take care of this.  If you a stack was printed for an unhandled
  1264. exception in an interactive interpreter, delete sys.last_traceback
  1265. instead.
  1266.  
  1267. - There is code that deletes all objects when the interpreter exits,
  1268. but if your Python has been configured to support threads, it is not
  1269. called (because other threads may still be active).  You can define
  1270. your own cleanup function using sys.exitfunc (see question 4.4).
  1271.  
  1272. - Finally, if your __del__ method raises an exception, this will be
  1273. ignored.  Starting with Python 1.4beta3, a warning message is printed
  1274. to sys.stderr when this happens.
  1275.  
  1276. 4.18. Q. How do I change the shell environment for programs called
  1277. using os.popen() or os.system()?  Changing os.environ doesn't work.
  1278.  
  1279. A. Modifying the environment passed to subshells was left out of the
  1280. interpreter because there seemed to be no well-established portable
  1281. way to do it (in particular, some systems, have putenv(), others have
  1282. setenv(), and some have none at all).
  1283.  
  1284. However if all you want is to pass environment variables to the
  1285. commands run by os.system() or os.popen(), there's a simple solution:
  1286. prefix the command string with a couple of variable assignments and
  1287. export statements.  The following would be universal for popen:
  1288.  
  1289.         import os
  1290.         from commands import mkarg # nifty routine to add shell quoting
  1291.         def epopen(cmd, mode, env = {}):
  1292.                 # env is a dictionary of environment variables
  1293.                 prefix = ''
  1294.                 for key, value in env.items():
  1295.                         prefix = prefix + '%s=%s\n' % (key, mkarg(value)[1:])
  1296.                         prefix = prefix + 'export %s\n' % key
  1297.                 return os.popen(prefix + cmd, mode)
  1298.  
  1299. 4.19. Q. What is a class?
  1300.  
  1301. A. A class is the particular object type that is created by executing
  1302. a class statement.  Class objects are used as templates, to create
  1303. class instance objects, which embody both the data structure and
  1304. program routines specific to a datatype.
  1305.  
  1306. 4.20. Q. What is a method?
  1307.  
  1308. A. A method is a function that you normally call as
  1309. x.name(arguments...) for some object x.  The term is used for methods
  1310. of classes and class instances as well as for methods of built-in
  1311. objects.  (The latter have a completely different implementation and
  1312. only share the way their calls look in Python code.)  Methods of
  1313. classes (and class instances) are defined as functions inside the
  1314. class definition.
  1315.  
  1316. 4.21. Q. What is self?
  1317.  
  1318. A. Self is merely a conventional name for the first argument of a
  1319. method -- i.e. a function defined inside a class definition.  A method
  1320. defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for
  1321. some instance x of the class in which the definition occurs;
  1322. the called method will think it is called as meth(x, a, b, c).
  1323.  
  1324. 4.22. Q. What is a unbound method?
  1325.  
  1326. A. An unbound method is a method defined in a class that is not yet
  1327. bound to an instance.  You get an unbound method if you ask for a
  1328. class attribute that happens to be a function. You get a bound method
  1329. if you ask for an instance attribute.  A bound method knows which
  1330. instance it belongs to and calling it supplies the instance automatically;
  1331. an unbound method only knows which class it wants for its first
  1332. argument (a derived class is also OK).  Calling an unbound method
  1333. doesn't "magically" derive the first argument from the context -- you
  1334. have to provide it explicitly.
  1335.  
  1336. 4.23. Q. How do I call a method defined in a base class from a derived
  1337. class that overrides it?
  1338.  
  1339. A. If your class definition starts with "class Derived(Base): ..."
  1340. then you can call method meth defined in Base (or one of Base's base
  1341. classes) as Base.meth(self, arguments...).  Here, Base.meth is an
  1342. unbound method (see previous question).
  1343.  
  1344. 4.24. Q. How do I call a method from a base class without using the
  1345. name of the base class?
  1346.  
  1347. A. DON'T DO THIS.  REALLY.  I MEAN IT.  It appears that you could call
  1348. self.__class__.__bases__[0].meth(self, arguments...) but this fails when
  1349. a doubly-derived method is derived from your class: for its instances,
  1350. self.__class__.__bases__[0] is your class, not its base class -- so
  1351. (assuming you are doing this from within Derived.meth) you would start
  1352. a recursive call.
  1353.  
  1354. 4.25. Q. How can I organize my code to make it easier to change the base
  1355. class?
  1356.  
  1357. A. You could define an alias for the base class, assign the real base
  1358. class to it before your class definition, and use the alias throughout
  1359. your class.  Then all you have to change is the value assigned to the
  1360. alias.  Incidentally, this trick is also handy if you want to decide
  1361. dynamically (e.g. depending on availability of resources) which base
  1362. class to use.  Example:
  1363.  
  1364.         BaseAlias = <real base class>
  1365.         class Derived(BaseAlias):
  1366.                 def meth(self):
  1367.                         BaseAlias.meth(self)
  1368.                         ...
  1369.  
  1370. 4.26. Q. How can I find the methods or attributes of an object?
  1371.  
  1372. A. This depends on the object type.
  1373.  
  1374. For an instance x of a user-defined class, instance attributes are
  1375. found in the dictionary x.__dict__, and methods and attributes defined
  1376. by its class are found in x.__class__.__bases__[i].__dict__ (for i in
  1377. range(len(x.__class__.__bases__))).  You'll have to walk the tree of
  1378. base classes to find *all* class methods and attributes.
  1379.  
  1380. Many, but not all built-in types define a list of their method names
  1381. in x.__methods__, and if they have data attributes, their names may be
  1382. found in x.__members__.  However this is only a convention.
  1383.  
  1384. For more information, read the source of the standard (but
  1385. undocumented) module newdir.
  1386.  
  1387. 4.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
  1388.  
  1389. A. os.read() is a low-level function which takes a file descriptor (a
  1390. small integer).  os.popen() creates a high-level file object -- the
  1391. same type used for sys.std{in,out,err} and returned by the builtin
  1392. open() function.  Thus, to read n bytes from a pipe p created with
  1393. os.popen(), you need to use p.read(n).
  1394.  
  1395. 4.28. Q. How can I create a stand-alone binary from a Python script?
  1396.  
  1397. The demo script "Demo/scripts/freeze.py" does what you want.  (It's
  1398. actually not a demo but a support tool -- there is some extra code in
  1399. the interpreter to accommodate it.)  It requires that you have the
  1400. Python build tree handy, complete with all the lib*.a files.
  1401.  
  1402. This works by scanning your source recursively for import statements
  1403. (both forms) and looking for the modules on the standard Python path
  1404. as well as in the source directory (for built-in modules).  It then
  1405. "compiles" the modules written in Python to C code (array initializers
  1406. that can be turned into code objects using the marshal module) and
  1407. creates a custom-made config file that only contains those built-in
  1408. modules which are actually used in the program.  It then compiles the
  1409. generated C code and links it with the rest of the Python interpreter
  1410. to form a self-contained binary which acts exactly like your script.
  1411.  
  1412. Hint: the freeze program only works if your script's filename ends in
  1413. ".py".
  1414.  
  1415. 4.29. Q. What WWW tools are there for Python?
  1416.  
  1417. A. See the chapter titled "Internet and WWW" in the Library Reference
  1418. Manual.  There's also a web browser written in Python, called Grail --
  1419. see <URL:http://monty.cnri.reston.va.us/grail/>.
  1420.  
  1421. Steve Miale <smiale@cs.indiana.edu> has written a modular WWW browser
  1422. called Dancer.  An alpha version can be FTP'ed from
  1423. <URL:ftp://ftp.cs.indiana.edu/pub/smiale/dancer.tar.gz>.  (There are a
  1424. few articles about Dancer in the (hyper)mail archive
  1425. <URL:http://www.cwi.nl/~guido/hypermail/python-1994q3/index.html>.)
  1426.  
  1427. 4.30. Q. How do I run a subprocess with pipes connected to both input
  1428. and output?
  1429.  
  1430. A. This is really a UNIX question.  Also, in general, it is unwise to
  1431. do so, because you can easily cause a deadlock where the parent
  1432. process is blocked waiting for output from the child, while the child
  1433. is blocked waiting for input from the child.  This can be caused
  1434. because the parent expects the child to output more text than it does,
  1435. or it can be caused by data being stuck in stdio buffers due to lack
  1436. of flushing.  The Python parent can of course explicitly flush the data
  1437. it sends to the child before it reads any output, but if the child is
  1438. a naive C program it can easily have been written to never explicitly
  1439. flush its output, even if it is interactive, since flushing is
  1440. normally automatic.
  1441.  
  1442. In many cases, all you really need is to run some data through a
  1443. command and get the result back.  Unless the data is infinite in size,
  1444. the easiest (and often the most efficient!) way to do this is to write
  1445. it to a temporary file and run the command with that temporary file as
  1446. input.  The standard module tempfile exports a function mktemp() which
  1447. generates unique temporary file names.
  1448.  
  1449. If after reading all of the above you still want to connect two pipes
  1450. to a subprocess's standard input and output, here's a simple solution,
  1451. due to Jack Jansen:
  1452.  
  1453.         import os
  1454.         import sys
  1455.         import string
  1456.  
  1457.         MAXFD = 100     # Max number of file descriptors in this system
  1458.  
  1459.         def popen2(cmd):
  1460.                 cmd = string.split(cmd)
  1461.                 p2cread, p2cwrite = os.pipe()
  1462.                 c2pread, c2pwrite = os.pipe()
  1463.                 pid = os.fork()
  1464.                 if pid == 0:
  1465.                         # Child
  1466.                         os.close(0)
  1467.                         os.close(1)
  1468.                         if os.dup(p2cread) != 0:
  1469.                                 sys.stderr.write('popen2: bad read dup\n')
  1470.                         if os.dup(c2pwrite) != 1:
  1471.                                 sys.stderr.write('popen2: bad write dup\n')
  1472.                         for i in range(3, MAXFD):
  1473.                                 try:
  1474.                                         os.close(i)
  1475.                                 except:
  1476.                                         pass
  1477.                         try:
  1478.                                 os.execv(cmd[0], cmd)
  1479.                         finally:
  1480.                                 os._exit(1)
  1481.                 os.close(p2cread)
  1482.                 tochild = os.fdopen(p2cwrite, 'w')
  1483.                 os.close(c2pwrite)
  1484.                 fromchild = os.fdopen(c2pread, 'r')
  1485.                 return fromchild, tochild
  1486.  
  1487. Note that many interactive programs (e.g. vi) don't work well with
  1488. pipes substituted for standard input and output.  You will have to use
  1489. pseudo ttys ("ptys") instead of pipes.  There is some undocumented
  1490. code to use these in the library module pty.py -- I'm afraid you're on
  1491. your own here.
  1492.  
  1493. A different answer is a Python interface to Don Libes' "expect"
  1494. library.  A prerelease of this is available on the Python ftp mirror
  1495. sites in the contrib subdirectory as expy-0.3.tar.gz, e.g.
  1496. <URL:ftp://ftp.python.org/pub/python/contrib/expy-0.3.tar.gz>.
  1497.  
  1498. 4.31. Q. How do I call a function if I have the arguments in a tuple?
  1499.  
  1500. A. Use the built-in function apply().  For instance,
  1501.  
  1502.     func(1, 2, 3)
  1503.  
  1504. is equivalent to
  1505.  
  1506.     args = (1, 2, 3)
  1507.     apply(func, args)
  1508.  
  1509. Note that func(args) is not the same -- it calls func() with exactly
  1510. one argument, the tuple args, instead of three arguments, the integers
  1511. 1, 2 and 3.
  1512.  
  1513. 4.32. Q. How do I enable font-lock-mode for Python in Emacs?
  1514.  
  1515. A. Assuming you're already using python-mode and font-lock-mode
  1516. separately, all you need to do is put this in your .emacs file:
  1517.  
  1518.         (defun my-python-mode-hook ()
  1519.           (setq font-lock-keywords python-font-lock-keywords)
  1520.           (font-lock-mode 1))
  1521.         (add-hook 'python-mode-hook 'my-python-mode-hook)
  1522.  
  1523. 4.33. Q. Is there an inverse to the format operator (a la C's scanf())?
  1524.  
  1525. A. Not as such.
  1526.  
  1527. For simple input parsing, the easiest approach is usually to split
  1528. the line into whitespace-delimited words using string.split(), and to
  1529. convert decimal strings to numeric values using string.atoi(),
  1530. string.atol() or string.atof().  (Python's atoi() is 32-bit and its
  1531. atol() is arbitrary precision.)  If you want to use another delimiter
  1532. than whitespace, use string.splitfield() (possibly combining it with
  1533. string.strip() which removes surrounding whitespace from a string).
  1534.  
  1535. For more complicated input parsing, regular expressions (see module
  1536. regex) are better suited and more powerful than C's scanf().
  1537.  
  1538. 4.34. Q. Can I have Tk events handled while waiting for I/O?
  1539.  
  1540. A. Yes, and you don't even need threads!  But you'll have to
  1541. restructure your I/O code a bit.  Tk has the equivalent of Xt's
  1542. XtAddInput() call, which allows you to register a callback function
  1543. which will be called from the Tk mainloop when I/O is possible on a
  1544. file descriptor.  Here's what you need:
  1545.  
  1546.         from Tkinter import tkinter
  1547.         tkinter.createfilehandler(file, mask, callback)
  1548.  
  1549. The file may be a Python file or socket object (actually, anything
  1550. with a fileno() method), or an integer file descriptor.  The mask is
  1551. one of the constants tkinter.READABLE or tkinter.WRITABLE.  The
  1552. callback is called as follows:
  1553.  
  1554.         callback(file, mask)
  1555.  
  1556. You must unregister the callback when you're done, using
  1557.  
  1558.         tkinter.deletefilehandler(file)
  1559.  
  1560. Note: since you don't know *how many bytes* are available for reading,
  1561. you can't use the Python file object's read or readline methods, since
  1562. these will insist on reading a predefined number of bytes.  For
  1563. sockets, the recv() or recvfrom() methods will work fine; for other
  1564. files, use os.read(file.fileno(), maxbytecount).
  1565.  
  1566. 4.35. Q. How do I write a function with output parameters (call by reference)?
  1567.  
  1568. A. [Mark Lutz] The thing to remember is that arguments are passed by
  1569. assignment in Python.  Since assignment just creates references to
  1570. objects, there's no alias between an argument name in the caller and
  1571. callee, and so no call-by-reference per se.  But you can simulate it
  1572. in a number of ways:
  1573.  
  1574. 1) By using global variables; but you probably shouldn't :-)
  1575.  
  1576. 2) By passing a mutable (changeable in-place) object:
  1577.  
  1578.       def func1(a):
  1579.           a[0] = 'new-value'     # 'a' references a mutable list
  1580.           a[1] = a[1] + 1        # changes a shared object
  1581.  
  1582.       args = ['old-value', 99]
  1583.       func1(args)
  1584.       print args[0], args[1]     # output: new-value 100
  1585.  
  1586. 3) By return a tuple, holding the final values of arguments:
  1587.  
  1588.       def func2(a, b):
  1589.           a = 'new-value'        # a and b are local names
  1590.           b = b + 1              # assigned to new objects
  1591.           return a, b            # return new values
  1592.  
  1593.       x, y = 'old-value', 99
  1594.       x, y = func2(x, y)
  1595.       print x, y                 # output: new-value 100
  1596.  
  1597. 4) And other ideas that fall-out from Python's object model. For
  1598.    instance, it might be clearer to pass in a mutable dictionary:
  1599.  
  1600.       def func3(args):
  1601.           args['a'] = 'new-value'     # args is a mutable dictionary
  1602.           args['b'] = args['b'] + 1   # change it in-place
  1603.  
  1604.       args = {'a':' old-value', 'b': 99}
  1605.       func3(args)
  1606.       print args['a'], args['b']
  1607.  
  1608. 5) Or bundle-up values in a class instance:
  1609.  
  1610.       class callByRef:
  1611.           def __init__(self, **args):
  1612.               for (key, value) in args.items():
  1613.                   setattr(self, key, value)
  1614.  
  1615.       def func4(args):
  1616.           args.a = 'new-value'        # args is a mutable callByRef
  1617.           args.b = args.b + 1         # change object in-place
  1618.  
  1619.       args = callByRef(a='old-value', b=99)
  1620.       func4(args)
  1621.       print args.a, args.b
  1622.  
  1623.    But there's probably no good reason to get this complicated :-).
  1624.  
  1625. [Python' author favors solution 3 in most cases.]
  1626.  
  1627. 4.36. Q. Please explain the rules for local and global variables in Python.
  1628.  
  1629. A. [Ken Manheimer] In Python, procedure variables are implicitly
  1630. global, unless they assigned anywhere within the block.  In that case
  1631. they are implicitly local, and you need to explicitly declare them as
  1632. 'global'.
  1633.  
  1634. Though a bit surprising at first, a moments consideration explains
  1635. this.  On one hand, requirement of 'global' for assigned vars provides
  1636. a bar against unintended side-effects.  On the other hand, if global
  1637. were required for all global references, you'd be using global all the
  1638. time.  Eg, you'd have to declare as global every reference to a
  1639. builtin function, or to a component of an imported module.  This
  1640. clutter would defeat the usefulness of the 'global' declaration for
  1641. identifying side-effects.
  1642.  
  1643. 4.37. Q. How can I have modules that mutually import each other?
  1644.  
  1645. A. Jim Roskind recommends the following order in each module:
  1646.  
  1647. First: all exports (like globals, functions, and classes that don't
  1648. need imported bases classes).
  1649.  
  1650. Then: all import statements.
  1651.  
  1652. Finally: all active code (including globals that are initialized from
  1653. imported values).
  1654.  
  1655. Python's author doesn't like this approach much because the imports
  1656. appear in a strange place, but has to admit that it works.  His
  1657. recommended strategy is to avoid all uses of "from <module> import *"
  1658. (so everything from an imported module is referenced as
  1659. <module>.<name>) and to place all code inside functions.
  1660. Initializations of global variables and class variables should use
  1661. constants or built-in functions only.
  1662.  
  1663. 4.38. Q. How do I copy an object in Python?
  1664.  
  1665. A. There is no generic copying operation built into Python, however
  1666. most object types have some way to create a clone.  Here's how for the
  1667. most common objects:
  1668.  
  1669. - For immutable objects (numbers, strings, tuples), cloning is
  1670. unnecessary since their value can't change.
  1671.  
  1672. - For lists (and generally for mutable sequence types), a clone is
  1673. created by the expression l[:].
  1674.  
  1675. - For dictionaries, the following function returns a clone:
  1676.  
  1677.         def dictclone(o):
  1678.             n = {}
  1679.             for k in o.keys(): n[k] = o[k]
  1680.             return n
  1681.  
  1682. - Finally, for generic objects, the "copy" module defines two
  1683. functions for copying objects.  copy.copy(x) returns a copy as shown
  1684. by the above rules.  copy.deepcopy(x) also copies the elements of
  1685. composite objects.  See the section on this module in the Library
  1686. Reference Manual.
  1687.  
  1688. 4.39. Q. How to implement persistent objects in Python?  (Persistent ==
  1689. automatically saved to and restored from disk.)
  1690.  
  1691. A. The library module "pickle" now solves this in a very general way
  1692. (though you still can't store things like open files, sockests or
  1693. windows), and the library module "shelve" uses pickle and (g)dbm to
  1694. create presistent mappings containing arbitrary Python objects.
  1695.  
  1696. 4.40. Q. I try to use __spam and I get an error about _SomeClassName__spam.
  1697.  
  1698. A. Variables with double leading underscore are "mangled" to provide a
  1699. simple but effective way to define class private variables.  See the
  1700. chapter "New in Release 1.4" in the Python Tutorial.
  1701.  
  1702.  
  1703. 5. Extending Python
  1704. ===================
  1705.  
  1706. 5.1. Q. Can I create my own functions in C?
  1707.  
  1708. A. Yes, you can create built-in modules containing functions,
  1709. variables, exceptions and even new types in C.  This is explained in
  1710. the document "Extending and Embedding the Python Interpreter" (the
  1711. LaTeX file Doc/ext.tex).  Also read the chapter on dynamic loading.
  1712.  
  1713. 5.2. Q. Can I create my own functions in C++?
  1714.  
  1715. A. Yes, using the C-compatibility features found in C++.  Basically
  1716. you place extern "C" { ... } around the Python include files and put
  1717. extern "C" before each function that is going to be called by the
  1718. Python interpreter.  Global or static C++ objects with constructors
  1719. are probably not a good idea.
  1720.  
  1721. 5.3. Q. How can I execute arbitrary Python statements from C?
  1722.  
  1723. A. The highest-level function to do this is run_command() which takes
  1724. a single string argument which is executed in the context of module
  1725. __main__ and returns 0 for success and -1 when an exception occurred
  1726. (including SyntaxError).  If you want more control, use run_string();
  1727. see the source for run_command() in Python/pythonrun.c.
  1728.  
  1729. 5.4. Q. How can I evaluate an arbitrary Python expression from C?
  1730.  
  1731. A. Call the function run_string() from the previous question with the
  1732. start symbol eval_input; it then parses an expression, evaluates it
  1733. and returns its value.  See exec_eval() in Python/bltinmodule.c.
  1734.  
  1735. 5.5. Q. How do I extract C values from a Python object?
  1736.  
  1737. A. That depends on the object's type.  If it's a tuple,
  1738. gettuplesize(o) returns its length and gettupleitem(o, i) returns its
  1739. i'th item; similar for lists with getlistsize(o) and getlistitem(o,
  1740. i).  For strings, getstringsize(o) returns its length and
  1741. getstringvalue(o) a pointer to its value (note that Python strings may
  1742. contain null bytes so strlen() is not safe).  To test which type an
  1743. object is, first make sure it isn't NULL, and then use
  1744. is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
  1745.  
  1746. 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
  1747.  
  1748. A. You can't.  Use t = newtupleobject(n) instead, and fill it with
  1749. objects using settupleitem(t, i, o) -- note that this "eats" a
  1750. reference count of o.  Similar for lists with newlistobject(n) and
  1751. setlistitem(l, i, o).  Note that you *must* set all the tuple items to
  1752. some value before you pass the tuple to Python code --
  1753. newtupleobject(n) initializes them to NULL, which isn't a valid Python
  1754. value.
  1755.  
  1756. 5.7. Q. How do I call an object's method from C?
  1757.  
  1758. A. Here's a function (untested) that might become part of the next
  1759. release in some form.  It uses <stdarg.h> to allow passing the
  1760. argument list on to vmkvalue():
  1761.  
  1762.         object *call_method(object *inst, char *methodname, char *format, ...)
  1763.         {
  1764.                 object *method;
  1765.                 object *args;
  1766.                 object *result;
  1767.                 va_list va;
  1768.                 method = getattr(inst, methodname);
  1769.                 if (method == NULL) return NULL;
  1770.                 va_start(va, format);
  1771.                 args = vmkvalue(format, va);
  1772.                 va_end(va);
  1773.                 if (args == NULL) {
  1774.                         DECREF(method);
  1775.                         return NULL;
  1776.                 }
  1777.                 result = call_object(method, args);
  1778.                 DECREF(method);
  1779.                 DECREF(args);
  1780.                 return result;
  1781.         }
  1782.  
  1783. This works for any instance that has methods -- whether built-in or
  1784. user-defined.  You are responsible for eventually DECREF'ing the
  1785. return value.
  1786.  
  1787. To call, e.g., a file object's "seek" method with arguments 10, 0
  1788. (assuming the file object pointer is "f"):
  1789.  
  1790.         res = call_method(f, "seek", "(OO)", 10, 0);
  1791.         if (res == NULL) {
  1792.                 ... an exception occurred ...
  1793.         }
  1794.         else {
  1795.                 DECREF(res);
  1796.         }
  1797.  
  1798. Note that since call_object() *always* wants a tuple for the argument
  1799. list, to call a function without arguments, pass "()" for the format,
  1800. and to call a function with one argument, surround the argument in
  1801. parentheses, e.g. "(i)".
  1802.  
  1803. 5.8. Q. How do I catch the output from print_error()?
  1804.  
  1805. A. (Due to Mark Hammond):
  1806.  
  1807. * in Python code, define an object that supports the "write()" method.
  1808.  
  1809. * redirect sys.stdout and sys.stderr to this object.
  1810.  
  1811. * call print_error, or just allow the standard traceback mechanism to
  1812. work.
  1813.  
  1814. Then, the output will go wherever your write() method sends it.
  1815.  
  1816. 5.9. Q. How do I access a module written in Python from C?
  1817.  
  1818. A. You can get a pointer to the module object as follows:
  1819.  
  1820.         module = import_module("<modulename>");
  1821.  
  1822. If the module hasn't been imported yet (i.e. it is not yet present in
  1823. sys.modules), this initializes the module; otherwise it simply returns
  1824. the value of sys.modules["<modulename>"].  Note that it doesn't enter
  1825. the module into any namespace -- it only ensures it has been
  1826. initialized and is stored in sys.modules.
  1827.  
  1828. You can then access the module's attributes (i.e. any name defined in
  1829. the module) as follows:
  1830.  
  1831.         attr = getattr(module, "<attrname>");
  1832.  
  1833. Calling setattr(), to assign to variables in the module, also works.
  1834.  
  1835. 5.10. Q. How do I interface to C++ objects from Python?
  1836.  
  1837. A. Depending on your requirements, there are many approaches.  Begin
  1838. by reading the "Extending and Embedding" document (Doc/ext.tex, see
  1839. also <URL:http://www.python.org/doc/>).  Realize that for the Python
  1840. run-time system, there isn't a whole lot of difference between C and
  1841. C++ -- so the strategy to build a new Python type around a C structure
  1842. (pointer) type will also work for C++ objects.
  1843.  
  1844. Automatic generation of interfaces between Python and C++ is still at
  1845. the horizon -- parsing C++ header files requires an almost complete
  1846. C++ parser, and many features aren't easily translated from C++ to
  1847. Python: certain forms of operator oveloading, function overloading
  1848. (best approached by a varargs function which explicitly type-checks
  1849. its arguments), and reference arguments are just a number of features
  1850. that are hard to translate correctly if at all.
  1851.  
  1852. The hardest problem is to transparently translate the C++ class
  1853. hierarchy to Python, so that Python programs derive classes from C++
  1854. classes.  Given suitable constraints, this may be possible, but it
  1855. would require more space than I have in this FAQ to explain how.
  1856. In any case, you can get quite a bit done without this, using just the
  1857. existing classes from Python.
  1858.  
  1859. If this all seems rather daunting, that may be because it is -- C++
  1860. isn't exactly a baby to handle without gloves!  However, people have
  1861. accomplished amazing feats of interfacing between Python and C++, and
  1862. a detailed question posted to the Python list is likely to elicit some
  1863. interesting and useful responses.
  1864.  
  1865.  
  1866. 6. Python's design
  1867. ==================
  1868.  
  1869. 6.1. Q. Why isn't there a switch or case statement in Python?
  1870.  
  1871. A. You can do this easily enough with a sequence of
  1872. if... elif... elif... else.  There have been some proposals for switch
  1873. statement syntax, but there is no consensus (yet) on whether and how
  1874. to do range tests.
  1875.  
  1876. 6.2. Q. Why does Python use indentation for grouping of statements?
  1877.  
  1878. A. Basically I believe that using indentation for grouping is
  1879. extremely elegant and contributes a lot to the clarity of the average
  1880. Python program.  Most people learn to love this feature after a while.
  1881. Some arguments for it:
  1882.  
  1883. - Since there are no begin/end brackets there cannot be a disagreement
  1884. between grouping perceived by the parser and the human reader.  I
  1885. remember long ago seeing a C fragment like this:
  1886.  
  1887.         if (x <= y)
  1888.                 x++;
  1889.                 y--;
  1890.         z++;
  1891.  
  1892. and staring a long time at it wondering why y was being decremented
  1893. even for x > y...  (And I wasn't a C newbie then either.)
  1894.  
  1895. - Since there are no begin/end brackets, Python is much less prone to
  1896. coding-style conflicts.  In C there are loads of different ways to
  1897. place the braces (including the choice whether to place braces around
  1898. single statements in certain cases, for consistency).  If you're used
  1899. to reading (and writing) code that uses one style, you will feel at
  1900. least slightly uneasy when reading (or being required to write)
  1901. another style.
  1902.  
  1903. - Many coding styles place begin/end brackets on a line by themself.
  1904. This makes programs considerably longer and wastes valuable screen
  1905. space, making it harder to get a good overview over a program.
  1906. Ideally, a function should fit on one basic tty screen (say, 20
  1907. lines).  20 lines of Python are worth a LOT more than 20 lines of C.
  1908. This is not solely due to the lack of begin/end brackets (the lack of
  1909. declarations also helps, and the powerful operations of course), but
  1910. it certainly helps!
  1911.  
  1912. 6.3. Q. Why are Python strings immutable?
  1913.  
  1914. A. There are two advantages.  One is performance: knowing that a
  1915. string is immutable makes it easy to lay it out at construction time
  1916. -- fixed and unchanging storage requirements.  (This is also one of
  1917. the reasons for the distinction between tuples and lists.)  The
  1918. other is that strings in Python are considered as "elemental" as
  1919. numbers.  No amount of activity will change the value 8 to anything
  1920. else, and in Python, no amount of activity will change the string
  1921. "eight" to anything else.  (Adapted from Jim Roskind)
  1922.  
  1923. 6.4. Q. Why don't strings have methods like index() or sort(), like
  1924. lists?
  1925.  
  1926. A. Good question.  Strings currently don't have methods at all
  1927. (likewise tuples and numbers).  Long ago, it seemed unnecessary to
  1928. implement any of these functions in C, so a standard library module
  1929. "string" written in Python was created that performs string related
  1930. operations.  Since then, the cry for performance has moved most of
  1931. them into the built-in module strop (this is imported by module
  1932. string, which is still the preferred interface, without loss of
  1933. performance except during initialization).  Some of these functions
  1934. (e.g. index()) could easily be implemented as string methods instead,
  1935. but others (e.g. sort()) can't, since their interface prescribes that
  1936. they modify the object, while strings are immutable (see the previous
  1937. question).
  1938.  
  1939. 6.5. Q. Why does Python use methods for some functionality
  1940. (e.g. list.index()) but functions for other (e.g. len(list))?
  1941.  
  1942. A. Functions are used for those operations that are generic for a
  1943. group of types and which should work even for objects that don't have
  1944. methods at all (e.g. numbers, strings, tuples).  Also, implementing
  1945. len(), max(), min() as a built-in function is actually less code than
  1946. implementing them as methods for each type.  One can quibble about
  1947. individual cases but it's really too late to change such things
  1948. fundamentally now.
  1949.  
  1950. 6.6. Q. Why can't I derive a class from built-in types (e.g. lists or
  1951. files)?
  1952.  
  1953. A. This is caused by the relatively late addition of (user-defined)
  1954. classes to the language -- the implementation framework doesn't easily
  1955. allow it.  See the answer to question 4.2 for a work-around.  This
  1956. *may* be fixed in the (distant) future.
  1957.  
  1958. 6.7. Q. Why must 'self' be declared and used explicitly in method
  1959. definitions and calls?
  1960.  
  1961. A. By asking this question you reveal your C++ background. :-)
  1962. When I added classes, this was (again) the simplest way of
  1963. implementing methods without too many changes to the interpreter.  I
  1964. borrowed the idea from Modula-3.  It turns out to be very useful, for
  1965. a variety of reasons.
  1966.  
  1967. First, it makes it more obvious that you are using a method or
  1968. instance attribute instead of a local variable.  Reading "self.x" or
  1969. "self.meth()" makes it absolutely clear that an instance variable or
  1970. method is used even if you don't know the class definition by heart.
  1971. In C++, you can sort of tell by the lack of a local variable
  1972. declaration (assuming globals are rare or easily recognizable) -- but
  1973. in Python, there are no local variable declarations, so you'd have to
  1974. look up the class definition to be sure.
  1975.  
  1976. Second, it means that no special syntax is necessary if you want to
  1977. explicitly reference or call the method from a particular class.  In
  1978. C++, if you want to use a method from base class that is overridden in
  1979. a derived class, you have to use the :: operator -- in Python you can
  1980. write baseclass.methodname(self, <argument list>).  This is
  1981. particularly useful for __init__() methods, and in general in cases
  1982. where a derived class method wants to extend the base class method of
  1983. the same name and thus has to call the base class method somehow.
  1984.  
  1985. Lastly, for instance variables, it solves a syntactic problem with
  1986. assignment: since local variables in Python are (by definition!) those
  1987. variables to which a value assigned in a function body (and that
  1988. aren't explicitly declared global), there has to be some way to tell
  1989. the interpreter that an assignment was meant to assign to an instance
  1990. variable instead of to a local variable, and it should preferably be
  1991. syntactic (for efficiency reasons).  C++ does this through
  1992. declarations, but Python doesn't have declarations and it would be a
  1993. pity having to introduce them just for this purpose.  Using the
  1994. explicit "self.var" solves this nicely.  Similarly, for using instance
  1995. variables, having to write "self.var" means that references to
  1996. unqualified names inside a method don't have to search the instance's
  1997. directories.
  1998.  
  1999. 6.8. Q. Can't you emulate threads in the interpreter instead of
  2000. relying on an OS-specific thread implementation?
  2001.  
  2002. A. Unfortunately, the interpreter pushes at least one C stack frame
  2003. for each Python stack frame.  Also, extensions can call back into
  2004. Python at almost random moments.  Therefore a complete threads
  2005. implementation requires thread support for C.
  2006.  
  2007. 6.9. Q. Why can't lambda forms contain statements?
  2008.  
  2009. A. Python lambda forms cannot contain statements because Python's
  2010. syntactic framework can't handle statements nested inside expressions.
  2011.  
  2012. However, in Python, this is not a serious problem.  Unlike lambda
  2013. forms in other languages, where they add functionality, Python lambdas
  2014. are only a shorthand notation if you're too lazy to define a function.
  2015.  
  2016. Functions are already first class objects in Python, and can be
  2017. declared in a local scope.  Therefore the only advantage of using a
  2018. lambda form instead of a locally-defined function is that you'll have
  2019. to invent a name for the function -- but that's just a local variable
  2020. to which the function object (which is exactly the same type of object
  2021. that a lambda form yields) is assigned!
  2022.  
  2023. 6.10. Q. Why don't lambdas have access to variables defined in the
  2024. containing scope?
  2025.  
  2026. A. Because they are implemented as ordinary functions.
  2027. See question 4.5 above.
  2028.  
  2029. 6.11. Q. Why can't recursive functions be defined inside other functions?
  2030.  
  2031. A. See question 4.5 above.
  2032.  
  2033. 6.12. Q. Why is there no more efficient way of iterating over a dictionary
  2034. than first constructing the list of keys()?
  2035.  
  2036. A. Have you tried it?  I bet it's fast enough for your purposes!  In
  2037. most cases such a list takes only a few percent of the space occupied
  2038. by the dictionary -- it needs only 4 bytes (the size of a pointer) per
  2039. key -- a dictionary costs 8 bytes per key plus between 30 and 70
  2040. percent hash table overhead, plus the space for the keys and values --
  2041. by necessity all keys are unique objects and a string object (the most
  2042. common key type) costs at least 18 bytes plus the length of the
  2043. string.  Add to that the values contained in the dictionary, and you
  2044. see that 4 bytes more per item really isn't that much more memory...
  2045.  
  2046. A call to dict.keys() makes one fast scan over the dictionary
  2047. (internally, the iteration function does exist) copying the pointers
  2048. to the key objects into a pre-allocated list object of the right size.
  2049. The iteration time isn't lost (since you'll have to iterate anyway --
  2050. unless in the majority of cases your loop terminates very prematurely
  2051. (which I doubt since you're getting the keys in random order).
  2052.  
  2053. I don't expose the dictionary iteration operation to Python
  2054. programmers because the dictionary shouldn't be modified during the
  2055. entire iteration -- if it is, there's a very small chance that the
  2056. dictionary is reorganized because the hash table becomes too full, and
  2057. then the iteration may miss some items and see others twice.  Exactly
  2058. because this only occurs rarely, it would lead to hidden bugs in
  2059. programs: it's easy never to have it happen during test runs if you
  2060. only insert or delete a few items per iteration -- but your users will 
  2061. surely hit upon it sooner or later.
  2062.  
  2063. 6.13. Q. Can Python be compiled to machine code, C or some other language?
  2064.  
  2065. A. Not easily.  Python's high level data types, dynamic typing of
  2066. objects and run-time invocation of the interpreter (using eval() or
  2067. exec) together mean that a "compiled" Python program would probably
  2068. consist mostly of calls into the Python run-time system, even for
  2069. seemingly simple operations like "x+1".  Thus, the performance gain
  2070. would probably be minimal.
  2071.  
  2072. Internally, Python source code is always translated into a "virtual
  2073. machine code" or "byte code" representation before it is interpreted
  2074. (by the "Python virtual machine" or "bytecode interpreter").  In order
  2075. to avoid the overhead of parsing and translating modules that rarely
  2076. change over and over again, this byte code is written on a file whose
  2077. name ends in ".pyc" whenever a module is parsed (from a file whose
  2078. name ends in ".py").  When the corresponding .py file is changed, it
  2079. is parsed and translated again and the .pyc file is rewritten.  There
  2080. is no performance difference once the .pyc file has been loaded (the
  2081. bytecode read from the .pyc file is exactly the same as the bytecode
  2082. created by direct translation).  The only difference is that loading
  2083. code from a .pyc file is faster than parsing and translating a .py
  2084. file, so the presence of precompiled .pyc files will generally improve
  2085. start-up time of Python scripts.  If desired, the Lib/compileall.py
  2086. module/script can be used to force creation of valid .pyc files for a
  2087. given set of modules.
  2088.  
  2089. If you are looking for a way to translate Python programs in order to
  2090. distribute them in binary form, without the need to distribute the
  2091. interpreter and library as well, have a look at the freeze.py script
  2092. in the Tools/freeze directory.  This creates a single binary file
  2093. incorporating your program, the Python interpreter, and those parts of
  2094. the Python library that are needed by your program.  Of course, the
  2095. resulting binary will only run on the same type of platform as that
  2096. used to create it.
  2097.  
  2098. Hints for proper usage of freeze.py:
  2099.  
  2100. - the script must be in a file whose name ends in .py
  2101.  
  2102. - you must have installed Python fully:
  2103.  
  2104.         make install
  2105.         make libinstall
  2106.         make inclinstall
  2107.         make libainstall
  2108.  
  2109. 6.14. Q. Why doesn't Python use proper garbage collection?
  2110.  
  2111. A. It's looking less and less likely that Python will ever get
  2112. "automatic" garbage collection (GC).  For one thing, unless this were
  2113. added to C as a standard feature, it's a portability pain in the ass.
  2114. And yes, I know about the Xerox library.  It has bits of assembler
  2115. code for *most* *common* platforms.  Not for all.  And although it is
  2116. mostly transparent, it isn't completely transparent (when I once
  2117. linked Python with it, it dumped core).
  2118.  
  2119. "Proper" GC also becomes a problem when Python gets embedded into
  2120. other applications.  While in a stand-alone Python it may be fine to
  2121. replace the standard malloc() and free() with versions provided by the
  2122. GC library, an application embedding Python may want to have its *own*
  2123. substitute for malloc() and free(), and may not want Python's.  Right
  2124. now, Python works with anything that implements malloc() and free()
  2125. properly.
  2126.  
  2127. Besides, the predictability of destructor calls in Python is kind of
  2128. attractive.  With GC, the following code (which is fine in current
  2129. Python) will run out of file descriptors long before it runs out of
  2130. memory:
  2131.  
  2132.         for file in <very long list of files>:
  2133.                 f = open(file)
  2134.                 c = file.read(1)
  2135.  
  2136. Using the current reference counting and destructor scheme, each new
  2137. assignment to f closes the previous file.  Using GC, this is not
  2138. guaranteed.  Sure, you can think of ways to fix this.  But it's not
  2139. off-the-shelf technology.
  2140.  
  2141.  
  2142. 7. Using Python on non-UNIX platforms
  2143. =====================================
  2144.  
  2145. 7.1. Q. Is there a Mac version of Python?
  2146.  
  2147. A. Yes, see the "mac" subdirectory of the distribution sites,
  2148. e.g. <URL:ftp://ftp.python.org/pub/python/mac/>.
  2149.  
  2150. 7.2. Q. Are there DOS and Windows versions of Python?
  2151.  
  2152. A. Yes.  There is a plethora of not-always-compatible versions.  See
  2153. the "pythonwin", "wpy", "nt" and "pc" subdirectories of the
  2154. distribution sites.  A quick comparison:
  2155.  
  2156. PythonWin: Extensive support for the 32-bit native Windows API and GUI
  2157. building using MFC.  Windows NT and Windows 95 only (and Windows
  2158. 3.1(1) using win32s, until Microsoft stops supporting it :-( ).
  2159. <URL:ftp://ftp.python.org/pub/python/pythonwin/>.
  2160.  
  2161. WPY: Ports to DOS, Windows 3.1(1), Windows 95, Windows NT and OS/2.
  2162. Also contains a GUI package that offers portability between Windows 
  2163. (not DOS) and Unix, and native look and feel on both.
  2164. <URL:ftp://ftp.python.org/pub/python/wpy/>.
  2165.  
  2166. NT: Basic ports built straight from the 1.4 distribution for Windows
  2167. 95 and Windows NT.  This will eventually provide core support for
  2168. both PythonWin and WPY on all 32-bit Microsoft platforms.
  2169. <URL:ftp://ftp.python.org/pub/python/nt/>.
  2170.  
  2171. PC: Old, unsupported ports to DOS, Windows 3.1(1) and OS/2.
  2172. <URL:ftp://ftp.python.org/pub/python/pc/>.
  2173.  
  2174. 7.3. Q. Is there an OS/2 version of Python?
  2175.  
  2176. A. Yes, see the "pc" and "wpy" subdirectory of the distribution sites
  2177. (see above).
  2178.  
  2179. 7.4. Q. Is there a VMS version of Python?
  2180.  
  2181. A. Donn Cave <donn@cac.washington.edu> did a partial port.  The
  2182. results of his efforts are on public display in
  2183. <<URL:ftp://ftp.python.org/pub/python/contrib/vms.tar.gz/>.  Someone
  2184. else is working on a more complete port, for details watch the list.
  2185.  
  2186. 7.5. Q. What about IBM mainframes, or other non-UNIX platforms?
  2187.  
  2188. A. I haven't heard about these, except I remember hearing about an
  2189. OS/9 port and a port to Vxworks (both operating systems for embedded
  2190. systems).  If you're interested in any of this, go directly to the
  2191. newsgroup and ask there, you may find exactly what you need.  For
  2192. example, a port to MPE/iX 5.0 on HP3000 computers was just announced,
  2193. see <URL:http://www.allegro.com/software/>.
  2194.  
  2195. 7.6. Q. Where are the source or Makefiles for the non-UNIX versions?
  2196.  
  2197. A. The standard sources can (almost) be used.  Additional sources can
  2198. be found in the platform-specific subdirectories of the distribution.
  2199.  
  2200. 7.7. Q. What is the status and support for the non-UNIX versions?
  2201.  
  2202. A. I don't have access to most of these platforms, so in general I am
  2203. dependent on material submitted by volunteers(*).  However I strive to
  2204. integrate all changes needed to get it to compile on a particular
  2205. platform back into the standard sources, so porting of the next
  2206. version to the various non-UNIX platforms should be easy.
  2207.  
  2208. (*) For the Macintosh, that volunteer is me, with help from Jack
  2209. Jansen <jack@cwi.nl>.
  2210.  
  2211. 7.8. Q. I have a PC version but it appears to be only a binary.
  2212. Where's the library?
  2213.  
  2214. A. You still need to copy the files from the distribution directory
  2215. "python/Lib" to your system.  If you don't have the full distribution,
  2216. you can get the file lib<version>.tar.gz from most ftp sites carrying
  2217. Python; this is a subset of the distribution containing just those
  2218. files, e.g.  <URL:ftp://ftp.python.org/pub/python/src/lib1.1.tar.gz>.
  2219.  
  2220. Once you have installed the library, you need to point sys.path to it.
  2221. Assuming the library is in C:\misc\python\lib, the following commands
  2222. will point your Python interpreter to it (note the doubled backslashes
  2223. -- you can also use single forward slashes instead):
  2224.  
  2225.         >>> import sys
  2226.         >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
  2227.         >>>
  2228.  
  2229. For a more permanent effect, set the environment variable PYTHONPATH,
  2230. as follows (talking to a DOS prompt):
  2231.  
  2232.         C> SET PYTHONPATH=C:\misc\python\lib
  2233.  
  2234. 7.9. Q. Where's the documentation for the Mac or PC version?
  2235.  
  2236. A.  The documentation for the Unix version also applies to the Mac and
  2237. PC versions.  Where applicable, differences are indicated in the text.
  2238.  
  2239. 7.10. Q. The Mac (PC) version doesn't seem to have any facilities for
  2240. creating or editing programs apart from entering it interactively, and
  2241. there seems to be no way to save code that was entered interactively.
  2242. How do I create a Python program on the Mac (PC)?
  2243.  
  2244. A. Use an external editor.  On the Mac, BBEdit seems to be a popular
  2245. no-frills text editor.  I work like this: start the interpreter; edit
  2246. a module file using BBedit; import and test it in the interpreter;
  2247. edit again in BBedit; then use the built-in function reload() to
  2248. re-read the imported module; etc.
  2249.  
  2250. Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
  2251. anyone with a pulse could certainly figure out how to do the same on
  2252. MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
  2253. Not only can you easily resave and "reload()" from Python after making
  2254. changes, but since WinNot auto-copies to the clipboard any text you
  2255. select, you can simply select the entire procedure (function) which
  2256. you changed in WinNot, switch to QWPython, and shift-ins to reenter
  2257. the changed program unit."
  2258.